I remember how surprised I was when I found out that setState
was async. Now I stumbled upon a \"strange\" behaviour that doesn\'t fit into my understanding of
As linked section of the reference says,
React may batch multiple setState() calls into a single update for performance.
It shouldn't update state in batch, at least in React 16.
As extensively explained in related answer by Dan Abramov of React team, the state is currently updated in batch only from event listeners, also on synchronous setState
calls in lifecycle hooks (componentDidMount
, componentDidUpdate
). This is expected to be changed in React 17.
In React 16, unstable_batchedUpdates
should be explicitly used to unconditionally update the state in batch (a demo):
setTimeout(() => {
ReactDOM.unstable_batchedUpdates(() => {
this.changeProp1();
});
}, 100);