The reason for this is that
setState()
is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after a setState()
call. This means you should not rely on the current state when calling setState()
since you cannot be sure what that state will be. The solution is to pass a function to setState()
with the previous state as an argument. By doing this, you can avoid the problem of the user getting an old state value on access because of the asynchronous nature of setState()
.
Let's say the initial value of a counter is zero. After three consecutive increment operations, the value will only be incremented by one.
// assuming this.state.count === 0
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
// this.state.count === 1, not 3
If we pass a function to setState()
, the count will be incremented correctly.
Comments