score:3

Accepted answer

This happens because as this answer states React tries to batch setState calls and process them together when it can. But this is not the case with asynchronous computations because React (and anybody in general) can't predict and reproduce the order of setState's called asynchronously.

So in your case it fallbacks to just updating state 3 times.

score:1

You can got this answer from React.Component life cycle doc (https://reactjs.org/docs/react-component.html)

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. React Component Lifecycle

Use this method shouldComponentUpdate(). This method allows your Component to exit the Update life cycle if there is no reason to apply a new render. Out of the box, the shouldComponentUpdate() is a no-op that returns true. This means every time we start an Update in a Component, we will re-render.

I add more code

  shouldComponentUpdate = function(nextProps, nextState) {
    return nextState.value !== this.state.value;
  }

  // Change value will set after await
  runAsyncFunc = async() => {
    console.log('BEFORE AWAIT');
    this.setState({ value: 1 });
    this.setState({ value: 1 });
    this.setState({ value: 1 });

    await setTimeout(()=>{}, 2000);

    console.log('AFTER AWAIT');
    this.setState({ value: 2 });
    this.setState({ value: 2 });
    this.setState({ value: 2 });
  }

Check my Codepen

So if you want to prevent unnecessary render custom method shouldComponentUpdate


Related Query

More Query from same tag