I have a code in which state
should be incremented by 1 every 2 seconds. setState
is called inside setInterval
callback, but instead of using a typical form of setState
: setState(newState)
I used a callback form setState(() => {...})
and weird things started happening. Instead of incrementing by 1, the state is being incremented by 2.
Here's the simplification of the offending code:
const handler = () => {
let val = 0;
setInterval(() => {
setState(() => {
console.log("before inc", { val });
val = val + 1;
console.log("after inc\n--------", { val });
return val;
});
}, 2000);
}
The expected logs would be:
before inc {val: 0}
after inc {val: 1}
--------
before inc {val: 1}
after inc {val: 2}
--------
but instead I've got:
before inc{val: 0}
after inc {val: 1}
--------
before inc {val: 2}
after inc {val: 3}
--------
which is super weird. What is happening?
Playground: codesandbox