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. Accessing this.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:

Need help with your React project?

I've been developing and supporting production React applications since 2015. Since then, I've developed my own set of best practices when working with complex React codebases that help me deliver fast, scalable interfaces for the web.

Want to see if I can help with your project? Reach out below and I'll get back to you within 24 hours: