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:
setColorchanges the state.- The change in stage makes the Function Component execute again
- The new invoke of the Function Component reruns
let [color, setColor] = useState("red"); - This assigns the current state of
colorto thecolorvariable. - Time passes
- The arrow function passed to
setTimeoutruns. This has closed over the previouscolorvariable 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.
constApp = ()=>{
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 fireconst timer = setTimeout(() => {
console.log('timer: ', color);
}, 5000)
return (clearTimeout(timer));
},[])
return (
<divstyle={{backgroundColor:color, width: '40px', height: '40px'}} ></div>
)
}
ReactDOM.render(
<App />,
document.getElementById("react")
);<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><divid="react"></div>
Post a Comment for "Callback Doesn't Receive The Updated Version Of State Even When It Fires Well After State Changes"