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 flag
(a state) variable on click of the button.
const [flag, toggleFlag] = useState(false);
const data = useRef(null);
data.current = flag;
const _onClick = () => {
toggleFlag(!flag);
// toggleFlag(!data.current); // working
setTimeout(() => {
toggleFlag(!flag); // does not have latest value, why ?
// toggleFlag(!data.current); // working
}, 2000);
};
return (
<div className="App">
<button onClick={_onClick}>{flag ? "true" : "false"}</button>
</div>
);
I figured out some other way to overcome this problem like using useRef or useReducer, but is this correct or is there any other way to solve this with useState only?
Also, it would be really helpful if anyone explains why we get old value of state inside the setTimeout.
Sandbox URL - https://codesandbox.io/s/xp540ynomo
_onClick
get a new closure and a newflag
value on every render? – Lillith