Batching: Many Updates, One Render

Three setters in one click lead to one render, not three. Watch the queue fill up and empty in a single pass.

React · intermediate · 6 min · 16 steps · free

What you'll learn

Batching.jsx

import { useState } from 'react';

export default function Signup() {
  const [name, setName] = useState('');
  const [age, setAge] = useState(0);
  const [saved, setSaved] = useState(false);

  function fillIn() {
    setName('Ada');
    setAge(36);
    setSaved(true);
  }

  return (
    <div>
      <p>{saved ? `Saved ${name}, ${age}` : 'Not saved yet'}</p>
      <button onClick={fillIn}>Fill in and save</button>
    </div>
  );
}

Step by step

  1. React renders <Signup> for the first time: it calls the Signup function.
  2. useState runs for the first time, so React stores the starting value for name and returns it: "".
  3. useState runs for the first time, so React stores the starting value for age and returns it: 0.
  4. useState runs for the first time, so React stores the starting value for saved and returns it: false.
  5. Signup returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  6. React turns the JSX into real page elements and shows them: look at the Screen panel.
  7. You click the “Fill in and save” button. React calls its onClick handler.
  8. The first update is queued: name → "Ada". No render yet.
  9. The second: age → 36.
  10. The third: saved → true. Queued updates holds all three.
  11. The handler has finished, so React renders once and applies everything in the queue.
  12. useState returns the value React has kept for name: "Ada". The starting value is only used on the first render.
  13. useState returns the value React has kept for age: 36. The starting value is only used on the first render.
  14. useState returns the value React has kept for saved: true. The starting value is only used on the first render.
  15. Signup returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  16. All three changes reach the page together.

Common mistakes

Best practices

Key takeaways

Check yourself

Two setters in a setTimeout, React 18: renders?

Answer: One. Automatic batching.

When does React render after setters in a handler?

Answer: After the handler finishes

·

More in How Rendering Works