Reputation: 5121
Case 1
increaseScoreBy3 () {
this.setState({score : this.state.score + 1});
this.setState({score : this.state.score + 1});
this.setState({score : this.state.score + 1});
}
Case 2
increaseScoreBy3 () {
this.setState({score : ++this.state.score});
this.setState({score : ++this.state.score});
this.setState({score : ++this.state.score});
}
I was reading this article and got to know setState function of React is asynchronous. My question is why batching is being done in case 1 and not in case 2 ? According to the article react will batch the calls to setState so result should be same in both the cases, but it is not happening. Please give me a reason for this.
Upvotes: 1
Views: 148
Reputation: 7819
In case 2 you are using a JS operator that modify in place the store value, which is bad.
Upvotes: 1
Reputation: 37594
React may batch subsequent calls together there is no guarantee for that. There is even an example in the React Docs to that:
This form of setState() is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:
Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 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 previous state, we recommend using the updater function form, instead:
this.setState((prevState) => {
return {counter: prevState.quantity + 1};
});
In general it's a bad idea to rely on asynchronous value changes. This goes for anything async related.
Upvotes: 1