I suppose this is because how JS works, but you wouldn't have this problem with classes I suppose. In this code:
let [open, setOpen] = React.useState(false);
let [counter, setCounter] = React.useState(0);
function handleClick() {
setOpen(true);
setInterval(() => {
console.log(counter);
setCounter(counter + 1);
}, 2000);
}
If I call handleClick once (e.g. click button), the value logged on console is always 0 (despite state being updated each time).
This is probably because of the closure. But what if I wanted to see the most recent value of counter
in such setup?
With classes you could have done this.state.counter
and it would read latest value.
Is there some workaround with hooks?
demo.
Note: I found this question which asks basically the same. Somehow I didn't encounter it on initial search.