Recently I was working on React Hooks and got stuck with one problem/doubt?
Below is a basic implementation to reproduce the issue, Here I\'m just toggling fla
This boils down to how closures work in JavaScript. The function given to setTimeout will get the flag variable from the initial render, since flag is not mutated.
You could instead give a function as argument to toggleFlag. This function will get the correct flag value as argument, and what is returned from this function is what will replace the state.
Example
const { useState } = React;
function App() {
const [flag, toggleFlag] = useState(false);
const _onClick = () => {
toggleFlag(!flag);
setTimeout(() => {
toggleFlag(flag => !flag)
}, 2000);
};
return (
);
}
ReactDOM.render( , document.getElementById("root"));