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
The function given to setTimeout will get the flag variable from the _onClick function. The _onClick function gets created every render and "stores" the value which the flag variable gets on this render.
function App() {
const [flag, toggleFlag] = useState(false);
console.log("App thinks that flag is", flag);
const _onClick = () => {
console.log("_onClick thinks that flag is", flag);
toggleFlag(!flag);
setTimeout(() => {
console.log("setTimeout thinks that flag is", flag);
}, 100);
};
return (
);
}
Console:
App thinks that flag is false
_onClick thinks that flag is false
App thinks that flag is true
setTimeout thinks that flag is false
_onClick thinks that flag is true
App thinks that flag is false
setTimeout thinks that flag is true