I faced the unexpected problem when updating state. So, I have such event handler:
const handleClick = async () => {
await new Promise((resolve) => setTimeout(resolve, 3000));
setCount(count + 1);
};
And if I click a button that runs the above event handler then the amount of button clicks do not catch up with state updates. Sure, setCount((count) => count + 1);
can solve the problem.
But what is interesting is that if I have such event handler then all works fast:
const handleClick = () => {
setTimeout(() => console.log('hello'), 3000);
setCount(count + 1);
};
The question is why async event handler works slower then non-async event handler even if I have async function inside like setTimeout
. I thought due to batching React waits for the finish of async calculations like setTimeout
and it does not matter whether you have async or non-async event handler