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:

Building a new Digital Product? Read This First

You're about to build your first digital product, but you're terrified at the breadth of terminology and wary of consultants nickel-and-diming you.

My free book Why Software Projects Fail offers that framework. In this companion to your hiring and discovery process, you'll learn how to inform your next decisions and to empower yourself along the way.

In the book, you'll learn:

  • How to find and hire a trustworthy consultant
  • Why it's critical you pay for a software discovery
  • How to assess your consultant's bid
  • What to expect—and be wary of—during the development process
  • How to take control of your project

Enter your email address below and then click the "Send Me My Free Gift" button. I'll send you Why Software Projects Fail, and you'll be equipped for success on your next project.