Course contentsShow
← React
Lesson 420 of 2,39612. Rendering and BatchingFree lesson

Batching Example: Multiple setState Calls

See how three consecutive setState calls trigger only one render instead of three.

Batching Example: Multiple setState Calls

What you'll learn: How React combines multiple setState calls into a single render, even when you call them one after another in the same function.

Seeing Batching in Action

You've learned that React batches updates automatically. Now let's see it with real code.

Imagine you have three pieces of state and update all of them in one click:

function ProfileEditor() {
  const [name, setName] = useState('Alice');
  const [age, setAge] = useState(25);
  const [city, setCity] = useState('Boston');

  console.log('RENDER');

  const handleUpdate = () => {
    setName('Bob');
    setAge(30);
    setCity('Seattle');
    // Three setState calls, but only ONE render!
  };

  return (
    <div>
      <p>{name}, {age}, {city}</p>
      <button onClick={handleUpdate}>Update Profile</button>
    </div>
  );
}

When you click the button, you'll see 'RENDER' logged only once, not three times. React batched all three updates together.

Why This Matters

Without batching, updating three separate state variables would cause three re-renders. That means React would recalculate your component's JSX three times, compare three virtual DOM snapshots, and potentially update the real DOM three times. Wasteful!

Batching is like filling a shopping cart: instead of checking out after every single item (slow!), you add everything first, then check out once (fast!).

Key Takeaway: Multiple setState calls in the same event handler are batched into a single render, preventing unnecessary work and keeping your UI fast.