score:0

First, let's see what Dan Abramov has to say about this matter:

In current release, they will be batched together if you are inside a React event handler. React batches all setStates done during a React event handler, and applies them just before exiting its own browser event handler.

With current version, several setStates outside of event handlers (e.g. in network responses) will not be batched. So you would get two re-renders in that case.

Hmmm, so we can do setState from React event handler and outside of it. React event handler is the function we pass as a prop to the component.

If we take handleClickAwaitBefore and rewrite it without async-await we get something like this:

 function handleClickAwaitBefore() {
    console.clear();

    // Here we are in event handler and setState is batched
    mockAPI().then(function notEventHandlerAnyMore(){
       
       // Here we are in totally different function and setState is not batched any more
       console.log(fromAPI);

       console.log("Calling 1st setState()");
       updateBooleanState(false);

       console.log("Calling 2nd setState()");
       updateBooleanState(true);

       console.log("After 2nd setState()"); 
    })

  }

score:2

Async programming is very much about call stacks and event loops.
You can find a lot about it in this video: https://www.youtube.com/watch?v=8aGhZQkoFbQ

So, when you have awaits in between, setStates will fall into different stacks.
I believe this is the main reason why react doesn't batch them.


Related Query

More Query from same tag