Categories
javascript react-hooks reactjs

The useState set method is not reflecting a change immediately

630

I am trying to learn hooks and the useState method has made me confused. I am assigning an initial value to a state in the form of an array. The set method in useState is not working for me, both with and without the spread syntax.

I have made an API on another PC that I am calling and fetching the data which I want to set into the state.

Here is my code:

<div id="root"></div>

<script type="text/babel" defer>
// import React, { useState, useEffect } from "react";
// import ReactDOM from "react-dom";
const { useState, useEffect } = React; // web-browser variant

const StateSelector = () => {
  const initialValue = [
    {
      category: "",
      photo: "",
      description: "",
      id: 0,
      name: "",
      rating: 0
    }
  ];

  const [movies, setMovies] = useState(initialValue);

  useEffect(() => {
    (async function() {
      try {
        // const response = await fetch("http://192.168.1.164:5000/movies/display");
        // const json = await response.json();
        // const result = json.data.result;
        const result = [
          {
            category: "cat1",
            description: "desc1",
            id: "1546514491119",
            name: "randomname2",
            photo: null,
            rating: "3"
          },
          {
            category: "cat2",
            description: "desc1",
            id: "1546837819818",
            name: "randomname1",
            rating: "5"
          }
        ];
        console.log("result =", result);
        setMovies(result);
        console.log("movies =", movies);
      } catch (e) {
        console.error(e);
      }
    })();
  }, []);

  return <p>hello</p>;
};

const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
</script>

<script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

Neither setMovies(result) nor setMovies(...result) works.

I expect the result variable to be pushed into the movies array.

1

  • Are you able to see the changes moving console.log("movies =", movies); outsite the useEffect hook?

    Apr 3, 2021 at 8:33


740

Much like .setState() in class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

setMovies(result);
console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn’t have a callback pattern

useEffect(() => {
    // action on update of movies
}, [movies]);

As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));

15

  • 72

    Hi, what about calling useState inside a form submit handler ? I am working on validating a complex form, and I call inside submitHandler useState hooks and unfortunately changes are not immediate !

    – da45

    Apr 19, 2019 at 16:42


  • 4

    useEffect might not be the best solution though, since it doesn’t support asynchronous calls. So, if we would like to make some asynchronous validation on movies state change, we have no control over it.

    – RA.

    Aug 20, 2019 at 3:10

  • 7

    please note that while the advice is very good, the explanation of the cause can be improved – nothing to do with the fact whether or not the updater provided by useState hook is asynchronous, unlike this.state that could have been mutated if this.setState was synchronous, the Closure around const movies would remain the same even if useState provided a synchronous function – see the example in my answer

    – Aprillion

    Nov 20, 2019 at 19:26


  • 4

    setMovies(prevMovies => ([...prevMovies, ...result])); worked for me

    – Mihir

    Mar 31, 2020 at 20:07

  • 17

    It is logging the wrong result because you are logging a stale closure not because the setter is asynchronous. If async was the problem then you could log after a timeout, but you could set a timeout for an hour and still log the wrong result because async isn’t what is causing the problem.

    – HMR

    May 12, 2020 at 7:02


449

Additional details to the previous answer:

While React’s setState is asynchronous (both classes and hooks), and it’s tempting to use that fact to explain the observed behavior, it is not the reason why it happens.

TLDR: The reason is a closure scope around an immutable const value.


Solutions:

  • read the value in render function (not inside nested functions):

      useEffect(() => { setMovies(result) }, [])
      console.log(movies)
    
  • add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):

      useEffect(() => { setMovies(result) }, [])
      useEffect(() => { console.log(movies) }, [movies])
    
  • use a temporary variable:

      useEffect(() => {
        const newMovies = result
        console.log(newMovies)
        setMovies(newMovies)
      }, [])
    
  • use a mutable reference (if we don’t need a state and only want to remember the value – updating a ref doesn’t trigger re-render):

      const moviesRef = useRef(initialValue)
      useEffect(() => {
        moviesRef.current = result
        console.log(moviesRef.current)
      }, [])
    

Explanation why it happens:

If async was the only reason, it would be possible to await setState().

However, both props and state are assumed to be unchanging during 1 render.

Treat this.state as if it were immutable.

With hooks, this assumption is enhanced by using constant values with the const keyword:

const [state, setState] = useState('initial')

The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect, event handlers, inside any Promise or setTimeout).

Consider following fake, but synchronous, React-like implementation:

// sync implementation:

let internalState
let renderAgain

const setState = (updateFn) => {
  internalState = updateFn(internalState)
  renderAgain()
}

const useState = (defaultState) => {
  if (!internalState) {
    internalState = defaultState
  }
  return [internalState, setState]
}

const render = (component, node) => {
  const {html, handleClick} = component()
  node.innerHTML = html
  renderAgain = () => render(component, node)
  return handleClick
}

// test:

const MyComponent = () => {
  const [x, setX] = useState(1)
  console.log('in render:', x) // ✅
  
  const handleClick = () => {
    setX(current => current + 1)
    console.log('in handler/effect/Promise/setTimeout:', x) // ❌ NOT updated
  }
  
  return {
    html: `<button>${x}</button>`,
    handleClick
  }
}

const triggerClick = render(MyComponent, document.getElementById('root'))
triggerClick()
triggerClick()
triggerClick()
<div id="root"></div>

7

  • @AlJoslin at a first glance, that seems like a separate problem, even if it might be caused by closure scope. If you have a concrete question, please create a new stackoverflow question with code example and all…

    – Aprillion

    Jun 16, 2020 at 7:59

  • 2

    actually I just finished a rewrite with useReducer, following @kentcdobs article (ref below) which really gave me a solid result that suffers not one bit from these closure problems. (ref: kentcdodds.com/blog/how-to-use-react-context-effectively)

    – Al Joslin

    Jun 16, 2020 at 16:52


  • for some reason solution 2 is not working.. I get the callback, but the value is still empty. useEffect(() => { console.log(movies) }, [movies]) this prints nothing ..

    – ACV

    Oct 22, 2020 at 13:57

  • 1

    @ACV Solution 2 works fine for the original question. If you need to solve a different problem, YMMW, but I am still 100% sure that the quoted code works as documented and the problem is somewhere else.

    – Aprillion

    Oct 22, 2020 at 20:25


  • All of these solutions require the use of useEffect. My problem is that my “movies” equivalent is an object I get from a Context provider and can be changed by many other components. I don’t want to run the effect every time it’s changed because my effect isn’t setMovies – it’s a different function I need to call only when a particular change is made to movies – a change I’m not seeing when needed because of a stale context.

    – Matt Frei

    Mar 15 at 6:52

17

I know that there are already very good answers. But I want to give another idea how to solve the same issue, and access the latest ‘movie’ state, using my module react-useStateRef.

As you understand by using React state you can render the page every time the state change. But by using React ref, you can always get the latest values.

So the module react-useStateRef let you use state’s and ref’s together. It’s backward compatible with React.useState, so you can just replace the import statement

const { useEffect } = React
import { useState } from 'react-usestateref'

  const [movies, setMovies] = useState(initialValue);

  useEffect(() => {
    (async function() {
      try {

        const result = [
          {
            id: "1546514491119",
          },
        ];
        console.log("result =", result);
        setMovies(result);
        console.log("movies =", movies.current); // will give you the latest results
      } catch (e) {
        console.error(e);
      }
    })();
  }, []);

More information:

0