Why doesn't React immediately mutate state when calling setState?
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. Accessingthis.state
after 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
modifying handleChange
to the following will result in the console receiving
the updated state: