Skip to content Skip to sidebar Skip to footer

Callback Doesn't Receive The Updated Version Of State Even When It Fires Well After State Changes

I'm using a functional component. I'm aware setColor changes the value of color asynchronously. However, my callback function doesn't receive the updated version of color (blue) ev

Solution 1:

  1. setColor changes the state.
  2. The change in stage makes the Function Component execute again
  3. The new invoke of the Function Component reruns let [color, setColor] = useState("red");
  4. This assigns the current state of color to the color variable.
  5. Time passes
  6. The arrow function passed to setTimeout runs. This has closed over the previous color variable which was assigned the old state.

Solution 2:

Here is a snippet logging the color state value at various times and also showing the effect of cleaning up in the return of the useEffect. It only serves to illustrate the timeline that Quentin laid out in their answer.

const App = ()=>{
  const [color, setColor] = React.useState("red");
  
  console.log('outside: ', color);
  
  React.useEffect(() => {
    setColor("blue");
    console.log('inside: ', color);
    setTimeout(() => {
      console.log('inside-timed: ', color);
    }, 5000)
    
    // the cleaned-up timer won't fire
    const timer = setTimeout(() => {
      console.log('timer: ', color);
    }, 5000)

    return (clearTimeout(timer));
  },[])
  
 return (
  <div style={{backgroundColor: color, width: '40px', height: '40px'}} ></div>
 )
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Post a Comment for "Callback Doesn't Receive The Updated Version Of State Even When It Fires Well After State Changes"