What is automatic batching in React 18?

HardReact FundamentalsTheory Question

Hint

Think about setState calls inside a setTimeout or a promise callback, before and after React 18.

Full Answer

Batching means React groups several state updates into one re-render. React 17 only batched updates inside its own event handlers. React 18, with createRoot, batches everywhere: timeouts, promises, native event listeners.

function handleClick() {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React 17 and 18: one re-render
}

setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React 17: two re-renders
  // React 18: one re-render
}, 1000);

fetch('/api').then(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React 18: one re-render
});

Batching changes when React re-renders, not what state ends up as. Two setCount(count + 1) calls still read the same count, so the counter goes up by one — use the updater form c => c + 1 when the next value depends on the previous one.

To opt out for a specific update, wrap it in flushSync from react-dom.

💡 Automatic batching needs createRoot. Apps still on the legacy ReactDOM.render keep React 17 behaviour.

More React Fundamentals Questions

Practice this in a timed sprint

5 free questions, no signup required