Reputation: 861
Let's say that I have these two calls:
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment + 1
}));
Because setState is asynchronous, how is it guaranteed that the first call to it will execute first?
Upvotes: 6
Views: 276
Reputation: 8552
From the react documentation of setState() states that
setState()
enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. setState() is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment or add a value to a counter more than once in the same cycle, that will result in the equivalent of:
Object.assign(
previousState,
{counter: previousState.counter + props.increment},
{counter: previousState.counter + props.increment + 1},
...
)
Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:
this.setState((state) => {
return {counter: state.counter + 1};
});
Upvotes: 5