Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 20

Understanding Batching and Performance

Recommended resources

Hello! In our last lesson, we focused on making our useState hook type-safe with TypeScript, covering everything from simple type inference to advanced patterns like discriminated unions.

Introduction

Today, we're shifting our focus from what our state is to when and how it gets updated. When you call a state setter function like setCount(1), it might feel like the update happens instantly. However, React has a clever optimization strategy happening behind the scenes.

Our goal for this lesson is to describe the batching of state updates and its performance implications. We'll explore how React groups multiple state updates into a single operation to boost performance, why this can sometimes lead to unexpected behavior with "stale" state, and how this entire process has been streamlined in modern React.

This concept is fundamental to understanding React's performance model and writing efficient, bug-free components.


What is State Batching?

At its core, batching is React's process of grouping multiple state updates into a single re-render for better performance.

Imagine you're at a restaurant. You don't expect the waiter to run to the kitchen after you order your appetizer, then run back to take your main course order, and run to the kitchen again. Instead, the waiter takes your entire order (and maybe your friend's order too) and then goes to the kitchen just once.

React's state updates work similarly. When you trigger an event, like a button click, React doesn't immediately re-render the component for every single setState call. It waits for your event handler function to finish running, collects all the requested state updates, and then performs a single re-render with all the changes applied at once.

How React ACTUALLY works (DEEP DIVE 2023)

To see this in action, the video 'How React ACTUALLY works' provides a clear, practical demonstration of batching.

Please watch from 07:03 to 07:41. The example shows a click handler that updates two different state variables. Notice in the console that the component only re-renders once, not twice.

Why is Batching Important for Performance?

The main reason for batching is performance. The process of rendering a component involves creating a new Virtual DOM tree, comparing it with the old one (a process called "reconciliation"), and then updating the actual browser DOM. DOM manipulation is one of the most computationally expensive operations in a web browser.

By batching updates, React minimizes these expensive re-renders. If ten state variables change in a single click handler, batching ensures this results in just one render cycle, not ten.


The Challenge of Batched Updates: "Stale State"

This batching mechanism is highly efficient, but it introduces a common pitfall related to the concept of "State as a Snapshot," which we've touched on. When a component renders, it "captures" the state values for that specific render. Any event handlers created during that render will see that same, captured state.

Consider this component:

function Counter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1); // count is 0 here
    setCount(count + 1); // count is still 0 here
    setCount(count + 1); // count is still 0 here
  };

  return (
    <>
      <h1>{count}</h1>
      <button onClick={handleClick}>+3</button>
    </>
  );
}

You might expect clicking the button to increment the count to 3. However, it will only increment to 1. This is because all three setCount calls are using the count value from the initial render, which is 0. React receives three instructions: "set the count to 1," "set the count to 1," and "set the count to 1." It batches them, and the final result is... 1.

This is a classic "stale state" problem. To solve it, we need a way to tell React to calculate the next state based on the previous state in the queue, not the state from the last render. This is done using the functional update form.

Mastering React's useState: Direct vs. Functional Updates
This image illustrates the difference between a direct state update, which can fail with batching, and a functional update, which correctly queues changes.

The official React documentation provides an excellent, in-depth explanation of this queuing mechanism.

Queueing a Series of State Updates

Please read the article 'Queueing a Series of State Updates' from the official React docs. It explains the batching process with the waiter analogy and details how to use updater functions to correctly handle multiple updates to the same state variable.

Read the page from the beginning down to the section 'What happens if you replace state after updating it'. Pay close attention to the tables that show how React processes the queue of updates. This will solidify your understanding of how updater functions (n => n + 1) differ from direct value updates (setNumber(5)).

Test your understanding!

Given the following component, what will the count be after the button is clicked once?

function TrickyCounter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 5);      // Instruction 1
    setCount(c => c + 1);     // Instruction 2
    setCount(42);             // Instruction 3
    setCount(c => c * 2);     // Instruction 4
  };

  return <button onClick={handleClick}>Calculate</button>;
}
Show answer

The final count will be 86.

Here's how React processes the queue:

  1. setCount(count + 5): count is 0, so this adds "replace with 5" to the queue.
  2. setCount(c => c + 1): Adds the function c => c + 1 to the queue.
  3. setCount(42): Adds "replace with 42" to the queue. This instruction effectively ignores the previous "replace with 5" and the updater function c => c + 1 that came before it within the same batch.
  4. setCount(c => c * 2): Adds the function c => c * 2 to the queue.

During the render, React processes the final queue:

  • The last direct replacement was "replace with 42". This becomes the starting value.
  • The next item is the function c => c * 2. React calls it with the current value, 42.
  • The function returns 42 * 2 = 86.

React stores 86 as the final result.

Correction: The article you read notes that "Any other value (e.g. number 5) adds 'replace with 5' to the queue, ignoring what’s already queued." This is a simplification. In reality, all updates are added to the queue and processed in order. Let's re-trace:

  1. Queue: ["replace with 5"]
  2. Queue: ["replace with 5", c => c + 1]
  3. Queue: ["replace with 5", c => c + 1, "replace with 42"]
  4. Queue: ["replace with 5", c => c + 1, "replace with 42", c => c * 2]

Processing the queue starting with state 0:

  • "replace with 5": current value becomes 5.
  • c => c + 1: current value becomes 5 + 1 = 6.
  • "replace with 42": current value becomes 42.
  • c => c * 2: current value becomes 42 * 2 = 86.

The final answer is indeed 86. The key is that replacements and functions are processed sequentially.


The Evolution of Batching: Automatic Batching in React 18

For a long time, there was a significant "gotcha" with batching: it only worked automatically inside React event handlers (like onClick, onChange, etc.).

If you triggered state updates from an asynchronous context—like inside a Promise.then(), setTimeout, or a native browser event listener—React would not batch them. Each setState call would trigger its own immediate re-render, leading to performance issues and inconsistent behavior.

With the release of React 18, this all changed. React introduced Automatic Batching.

React 18 Automatic Batching Illustration
Automatic Batching in React 18 ensures all state updates, no matter where they are initiated, are grouped into a single re-render.

Now, all state updates are automatically batched, regardless of where they originate from. This creates more consistent behavior and better out-of-the-box performance.

Mastering React Batch Updating

The video 'Mastering React Batch Updating' by Jack Herrington provides an excellent side-by-side comparison of the old and new behavior.

Please watch from 02:59 to 05:36 to see the pre-React 18 problem, where updates inside a promise cause multiple re-renders. Then, watch from 06:23 to 07:55 to see how updating the project to React 18 and using its new createRoot API automatically fixes this problem.

As a software engineer, it's valuable to understand this history. You might work on older codebases that use React 17 or earlier, or you may see workarounds like unstable_batchedUpdates which were used to manually enable batching in async contexts. In any modern React 18+ application, these workarounds are no longer necessary.


Conclusion

Understanding state batching is key to grasping how React's rendering process is optimized for performance. It explains why setState calls can feel "asynchronous" and why certain update patterns are necessary.

Key Takeaways:

  • Batching for Performance: React groups multiple state updates within a single event loop tick into one re-render to prevent expensive, unnecessary UI updates.
  • Stale State & Functional Updates: When updating state based on its previous value, always use the functional update form (setState(prevState => ...)) to ensure you are working with the latest state from the queue, not a stale value from a previous render.
  • Automatic Batching in React 18: Modern React automatically batches all state updates, whether they are synchronous or asynchronous, leading to more predictable behavior and better performance by default.

Next Steps

We've now seen how to use the functional update form to solve the stale state problem caused by batching. In the next lesson, we will formalize this pattern and explore it more deeply as we cover the learning outcome: Update state based on the previous state using the functional update form. This will solidify your ability to handle complex state transitions reliably.