Why doesn't React immediately mutate state when calling setState? December 20, 2016
When setting the state on a React component within an event handler, you'll find that the state isn't updated if you dump the state to the console immediately after:
The React documentation warns:
setState()does not immediately mutate this.state but creates a pending state transition. Accessing
this.stateafter calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
I learned today that
setState accepts a callback in this scenario. So
handleChange to the following will result in the console receiving
the updated state: