2

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

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • `setTimeout(() => { console.log('hello'); setCount(count + 1); resolve()}, 3000);` – AdityaParab Jun 02 '23 at 11:34
  • 4
    It's not clear to me what you're asking. The first version will wait three seconds before updating state, because it's awaiting a timeout. The second version will not wait three seconds before updating state, because it's not awaiting a timeout. What unexpected behavior are you asking about? – David Jun 02 '23 at 11:37
  • One issue with `setCount` is that operation is asynchronous itself. https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync – epascarello Jun 02 '23 at 12:10
  • @David, haha you are right, my mistake. David, a question about the first version, if I put the awaiting timeout after setCount then state update works smooth. Why? As far as I know, React does batching and waits until it finishes all of the code in event handler. What I mean is that when React reaches the end of the event handler then I expect it would wait for 3 seconds due to setTimeout before doing the update but state is updated fast – user17893436 Jun 02 '23 at 12:36
  • 2
    @user17893436: You seem to be expecting React to perform some kind of magic any time the code involves an asynchronous operation. It doesn't. It does exactly what the code tells it to do. When you perform a state update, React internally queues/batches that state update (and any other such updates) to be performed when the "thread" is available. Awaiting another asynchronous operation makes it available. It's not clear what you're trying to accomplish in the code, it just seems that you're performing fairly random operations to test otherwise incorrect assumptions. – David Jun 02 '23 at 12:41

0 Answers0