How does React batch state updates?
Answer
Batching is React's optimization of grouping multiple state updates into a single re-render instead of rendering after each update. React 17 and earlier: batched updates only inside React event handlers. Updates inside setTimeout, Promises, native event handlers, etc. were NOT batched — each setState caused a separate render. React 18: Automatic Batching. All updates are automatically batched, regardless of where they originate — React event handlers, setTimeout, Promise callbacks, native event listeners. Example: setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); }, 1000); — with React 18, this causes one re-render, not two. Opting out: use flushSync() from react-dom to force a synchronous update without batching: flushSync(() => setCount(1)); // renders immediately. Use flushSync when you need the DOM to be updated synchronously before the next line (e.g., reading a DOM measurement after a state change). Batching is a performance optimization — it reduces unnecessary renders and prevents intermediate UI states from being visible.
Previous
What is the difference between useState and useReducer?
Next
What is React Concurrent Mode?