← Back to React, page 7

react-0121 · Medium mid

What is automatic batching in React 18, how did batching work before it, and how do you opt out with flushSync?

Batching groups several state updates into one re-render. Before React 18, React batched updates only inside React event handlers, so updates in timeouts, promises and native event handlers caused one render per setState. React 18 with createRoot batches all updates automatically, wherever they happen, within the same tick. To force a synchronous render for one update, wrap it in flushSync from react-dom, and use it rarely.

Full answer

A render is not free, so React avoids rendering after every setState. When several updates happen together, React waits and applies them in one pass.

React 17 and earlier. React batched only updates that ran inside its own event handlers. Inside the handler, setA(1); setB(2) gave one render. In a setTimeout, a fetch().then, or a native addEventListener callback, each setter caused its own synchronous re-render, so two updates rendered twice, and in between the UI could show half-updated state. Developers used ReactDOM.unstable_batchedUpdates to work around it.

React 18. With createRoot, all updates are batched automatically, whatever their origin: handlers, timeouts, promises, native events. The updates scheduled in the same tick lead to a single render. Apps that still use the legacy ReactDOM.render API (removed in React 19) keep the old behaviour, which is part of why migrating to createRoot matters.

Opting out. Rarely you need the DOM to be updated immediately between two updates, for example to measure the layout after the first. flushSync(() => setA(1)) from react-dom forces React to apply that update synchronously, then the following updates are handled separately. It can hurt performance and may flush pending effects, so treat it as an escape hatch.

Related ideas: updates inside a transition are batched and lower priority, setState with the updater form queues operations in order, and batching never changes the final state, only the number of renders.

The example counts renders after two updates in a timer, with and without flushSync.

jsx
import { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';

let api;
let renders = 0;

function Counter() {
  const [a, setA] = useState(0);
  const [b, setB] = useState(0);
  renders += 1;

  useEffect(() => {
    api = { setA, setB };
  }, []);

  return (
    <p>
      a={a}, b={b}
    </p>
  );
}

const container = document.getElementById('root');
createRoot(container).render(<Counter />);
const wait = () => new Promise((resolve) => setTimeout(resolve, 30));
await wait();

let before = renders;
setTimeout(() => {
  api.setA(1);
  api.setB(1);
});
await wait();
console.log('two updates in a timer: ' + (renders - before) + ' render(s)');

before = renders;
setTimeout(() => {
  flushSync(() => api.setA(2));
  api.setB(2);
});
await wait();
console.log('with flushSync around the first: ' + (renders - before) + ' render(s)');
console.log('final output: ' + container.textContent);

This ran as a script with React 19 and createRoot. The counter increments a module variable during render, which is acceptable only for a demo. Two updates in a timer rendered once, and flushSync made the first update render on its own. Output of the run: two updates in a timer: 1 render(s) with flushSync around the first: 2 render(s) final output: a=2, b=2

Key points

  • Batching groups multiple state updates into one render.
  • Before React 18, only updates in React event handlers were batched.
  • With createRoot in React 18 and later, all updates are batched automatically.
  • flushSync forces a synchronous render for the update inside it. Use it sparingly.
  • Batching changes the number of renders, not the final state.

Common mistakes

  • Assuming each setState call causes a render.
  • Using unstable_batchedUpdates in React 18 and later code.
  • Calling flushSync often and losing the performance benefit.
  • Expecting legacy ReactDOM.render apps to batch automatically.
  • Counting renders inside a component without Strict Mode in mind, which doubles them in development.

Follow-ups

  • Why does a legacy-root app not get automatic batching?
  • How does batching interact with transitions?
  • Which situations really need flushSync?

Tips

  • Tell the history in two steps: handlers only, then everything.
  • Say flushSync is an escape hatch with a cost.
  • Mention that batching changes render count, not the final result.