React may batch multiple setState()
calls into a single update for performance. Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
This counter example will fail to update as expected:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
})
The preferred approach is to call setState()
with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}))