Reputation: 41
In the official React docs for State and Lifecycle methods, section "State Updates May be Asynchronous: https://reactjs.org/docs/state-and-lifecycle.html
They say when updating state based on previous state, we should pass a function to setState() to get the previous state as the first argument:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
It's hard to imagine how the "Wrong" way can possibly lead to problems. What is an example of code where the "Wrong" way can lead to errors?
Upvotes: 1
Views: 48
Reputation: 836
For a case like this with just one call setState
there is nothing wrong. However, since React batches state update, it's not guaranteed to work. I can give you a simple example
this.setState({ count: this.state.count + 10 });
this.setState({ count: this.state.count + 1 });
//The end result is count+1 instead of count+11
//This will work correctly
this.setState((state) => ({count: state.count+10 }));
this.setState((state) => ({count: state.count+1 }));
Upvotes: 1