React setState: What Really Happens Under the Hood?
Javier Machin

May 18, 2019

React setState: What Really Happens Under the Hood?

Unraveling the intricate process behind React's state updates and lifecycle methods

engineeringreact

Available for senior roles & selected contracts email me

Let's look at one of React's most fundamental features: setState. It looks simple on the surface, but a fair amount happens when you call it.


The setState Trigger

When you call setState, React doesn't update the state immediately. Instead it records a 'pending state update' and schedules the work for later.


The Reconciliation Process

Once React has collected the pending state updates, it runs a process called reconciliation. It builds a new virtual DOM tree with your updated state, compares it against the current one, and works out the minimal set of changes needed to update the actual DOM.


Batching: React's Efficiency Trick

Instead of updating the DOM on every setState call, React batches multiple updates together and applies them in one pass.

  • This reduces the number of DOM manipulations, which is good for performance.
  • It keeps your component from re-rendering more than it needs to.

The Lifecycle Order

During this process, React calls several lifecycle methods in a specific order:

  1. getDerivedStateFromProps: Called after a component is instantiated or when it receives new props.
  2. shouldComponentUpdate: Determines if the component should re-render.
  3. render: Creates the new Virtual DOM.
  4. getSnapshotBeforeUpdate: Captures information from the DOM before changes are made.
  5. React updates DOM and refs
  6. componentDidUpdate: Called after the update is committed to the DOM.

For functional components using hooks, the process is similar but uses the useEffect hook instead of these lifecycle methods.


The Final Update

Once React has gone through all these steps:

  • It updates the actual DOM in one go.
  • It calls the final lifecycle method, componentDidUpdate.
  • Finally, it updates the state object of your component.

After that, your component reflects the new state. That's the full path a setState call takes.


Why This Matters

Understanding this process helps you:

  • Write more efficient React code
  • Debug state-related issues more effectively
  • Understand why state should be treated as immutable
  • Make better use of lifecycle methods

None of this changes how you call setState day to day, but knowing what happens underneath makes a lot of React's behaviour easier to predict.

React Hydration: What Is It and How Does It Work?

Understanding how React brings static HTML to life with interactive JavaScript

Oct 27, 2023Read more