Updating useState inside useReducer? Also my reducer is firing twice at the first dispatch called

Asked
Active3 hr before
Viewed126 times

11 Answers

usereducerreducerfiringtwicefirstdispatchcalledupdatinginsideusestate
90%

Electrical Engineering,Asking for help, clarification, or responding to other answers.,Software Quality Assurance & Testing

 Pretag team - issue, fix, solve, resolve
88%

You'll find the following block of code from React shown in that answer:

  var currentState = queue.eagerState;
  var _eagerState = _eagerReducer(currentState, action);
  // Stash the eagerly computed state, and the reducer used to compute
  // it, on the update object. If the reducer hasn't changed by the
  // time we enter the render phase, then the eager state can be used
  // without calling the reducer again.
  _update2.eagerReducer = _eagerReducer;
  _update2.eagerState = _eagerState;
  if (is(_eagerState, currentState)) {
     // Fast path. We can bail out without scheduling React to re-render.
     // It's still possible that we'll need to rebase this update later,
     // if the component re-renders for a different reason and by that
     // time the reducer has changed.
     return;
  }
load more v
72%

As stated above, this is expected behavior in some cases, and should be unobervable to your code because reducers should be pure.,If reducer is pure, and it has to be pure, nothing observable happens.,What is the expected behavior? when a dispatch() of OOTB useReducer is called, all instances should call the reduce() only once.

const [state, dispatch] = useReducer(reduce, {})
   ...
   dispatch({
      something_useful...
   }) //this call happens twice in the execution stack.
load more v
65%

Note : The reducer function should be defined separately outside the functional component. If it is defined within the component code, it implies that on a re-render, it provides a new reducer function each time even though the reducer code is identical. You may experience unexpected behavior if you define the reducer function code inside the component in terms of the hook getting called twice unexpectedly.,While defining a React component, we will need to identify all the parts of the component state. Once we have the parts identified, we can define State in any of the two ways mentioned below:,Now, we create the hook in our functional component passing the two values illustrated above as arguments i.e. the reducer function and the initial state.

 Pretag team - issue, fix, solve, resolve
75%

Basic Hooks useState useEffect useContext ,If you’re new to Hooks, you might want to check out the overview first. You may also find useful information in the frequently asked questions section.,Correct: useContext(MyContext)

const [state, setState] = useState(initialState);
load more v
40%

useReducer is used to store and update states, just like the useState Hook. It accepts a reducer function as its first parameter and the initial state as the second.,The dispatch is the second value returned from the useReducer Hook and can be used in our JSX to update the state.,The initial state is the second argument passed to the useReducer Hook, and it represents the default state.

Pretag
useReducer
load more v
22%

First, we need to call the useState Hook two times — first for the term, and again for the array of photos. In order to match the hook-less version of our app, we’ll pass the string “coding” as the initial term state, and an empty array for the initial photos state.,If it’s confusing now, don’t worry — I’m going to give an example in a moment. But first, we need to go over the useReducer Hook.,Here’s an example of a simple component that enables the user to select a region and a language:

Source: https://pirates.fandom.com/wiki/James_Hook
/n

If you’re a React engineer and you haven’t been living on the moon for the past nine months, chances are you’ve heard about React Hooks. The TL;DR is that before Hooks, class components were the only components that could track state and make requests to an API. Hooks are functions that enable us to use state and other React features in functional components. In this post, I’m going to walk you through four of the major Hooks — useState, useEffect, useContext, and useReducer — , all while refactoring the PhotoFinder app I built to go along with my 2018 post, “A Beginner’s Guide to React.” Let’s get started.

state
Source: https://pirates.fandom.com/wiki/James_Hook
/n

If you’re a React engineer and you haven’t been living on the moon for the past nine months, chances are you’ve heard about React Hooks. The TL;DR is that before Hooks, class components were the only components that could track state and make requests to an API. Hooks are functions that enable us to use state and other React features in functional components. In this post, I’m going to walk you through four of the major Hooks — useState, useEffect, useContext, and useReducer — , all while refactoring the PhotoFinder app I built to go along with my 2018 post, “A Beginner’s Guide to React.” Let’s get started.

state
Source: https://pirates.fandom.com/wiki/James_Hook
/n

If you’re a React engineer and you haven’t been living on the moon for the past nine months, chances are you’ve heard about React Hooks. The TL;DR is that before Hooks, class components were the only components that could track state and make requests to an API. Hooks are functions that enable us to use state and other React features in functional components. In this post, I’m going to walk you through four of the major Hooks — useState, useEffect, useContext, and useReducer — , all while refactoring the PhotoFinder app I built to go along with my 2018 post, “A Beginner’s Guide to React.” Let’s get started.

useState
Source: https://pirates.fandom.com/wiki/James_Hook
/n

If you’re a React engineer and you haven’t been living on the moon for the past nine months, chances are you’ve heard about React Hooks. The TL;DR is that before Hooks, class components were the only components that could track state and make requests to an API. Hooks are functions that enable us to use state and other React features in functional components. In this post, I’m going to walk you through four of the major Hooks — useState, useEffect, useContext, and useReducer — , all while refactoring the PhotoFinder app I built to go along with my 2018 post, “A Beginner’s Guide to React.” Let’s get started.

useEffect
Source: https://pirates.fandom.com/wiki/James_Hook
/n

If you’re a React engineer and you haven’t been living on the moon for the past nine months, chances are you’ve heard about React Hooks. The TL;DR is that before Hooks, class components were the only components that could track state and make requests to an API. Hooks are functions that enable us to use state and other React features in functional components. In this post, I’m going to walk you through four of the major Hooks — useState, useEffect, useContext, and useReducer — , all while refactoring the PhotoFinder app I built to go along with my 2018 post, “A Beginner’s Guide to React.” Let’s get started.

useContext
Source: https://pirates.fandom.com/wiki/James_Hook
/n

If you’re a React engineer and you haven’t been living on the moon for the past nine months, chances are you’ve heard about React Hooks. The TL;DR is that before Hooks, class components were the only components that could track state and make requests to an API. Hooks are functions that enable us to use state and other React features in functional components. In this post, I’m going to walk you through four of the major Hooks — useState, useEffect, useContext, and useReducer — , all while refactoring the PhotoFinder app I built to go along with my 2018 post, “A Beginner’s Guide to React.” Let’s get started.

useReducer
load more v
60%

When setState handler is called multiple times, React batches these calls and triggers re-render only once when the calling code is inside React based event handlers. If these calls are made from non-React based handlers like setTimeout, each call will trigger a re-render. (refer to this post on this topic),React runs useEffect handler after it fully synchronizes the current component state to DOM. This makes it an ideal place to initiate the side-effects (backend calls, registering subscriptions, logging, timers etc).,When long quote is set to the state, React commits the the full quote to the DOM.

Let’s understand the workings of useState with an example. We will implement the Ticker component as per the above sketch. The active ticker which is shown on the UI is stored in a local state using useState hook. Here is the relevant portion of the component (full code here).

const [ticker, setTicker] = useState("AAPL");...
const onChange = event => {
   setTicker(event.target.value);
}...
load more v
48%

Now we’ve entered useReducer territory. The reducer in ‘useReducer’ comes from Redux, which in turn borrowed it from JavaScript’s Array.reduce().,Let’s apply the reducer pattern and useReducer to our form from earlier:,In the context of React, here’s the typical pattern used with useReducer:

Live, editable JSX Snippet:
function Counter() {    const [count, setCount] = React.useState(0)    return (        <div>            <p>Count: {count}</p>            <button onClick={() => setCount(count + 1)}>                Increment            </button>        </div>    )}
load more v
23%

useReducer is one of a handful of React hooks that shipped in React 16.7.0. It accepts a reducer function with the application initial state, returns the current application state, then dispatches a function.,Our reducer function will handle two things: the addition and removal of new items.,Provide a function that contains actions that update the state.

Here is an example of how it is used;

const [state, dispatch] = useReducer(reducer, initialState);
load more v
90%

Hooks are a new addition in React that lets you use state and other React features without writing a class. This website provides easy to understand code examples to help you learn how hooks work and inspire you to take advantage of them in your next project.,react-async - React component and hook for declarative promise resolution and data fetching.,donavon/use-dark-mode - A more configurable implementation of this hook that syncs changes across browser tabs and handles SSR. Provided much of the code and inspiration for this post.

Basically, what this hook does is that, it takes a parameter with value true or false and toggles that value to opposite. It's useful when we want to take some action into it's opposite action, for example: show and hide modal, show more/show less text, open/close side menu.

import { useCallback, useState } from 'react';


// Usage
function App() {
    // Call the hook which returns, current value and the toggler function
    const [isTextChanged, setIsTextChanged] = useToggle();
    
    return (
        <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button>
    );
}

// Hook
// Parameter is the boolean, with default "false" value
const useToggle = (initialState = false) => {
    // Initialize the state
    const [state, setState] = useState(initialState);
    
    // Define and memorize toggler function in case we pass down the comopnent,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback(() => setState(state => !state), []);
    
    return [state, toggle]
}
import { useCallback, useState } from 'react';


// Usage
function App() {
    // Call the hook which returns, current value and the toggler function
    const [isTextChanged, setIsTextChanged] = useToggle();

    return (
        <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button>
    );
}

// Hook
// Parameter is the boolean, with default "false" value
const useToggle = (initialState: boolean = false): [boolean, any] => {
    // Initialize the state
    const [state, setState] = useState<boolean>(initialState);

    // Define and memorize toggler function in case we pass down the comopnent,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback((): void => setState(state => !state), []);

    return [state, toggle]
}
load more v

Other "usereducer-reducer" queries related to "Updating useState inside useReducer? Also my reducer is firing twice at the first dispatch called"