How does React batch state updates?
Why Interviewers Ask This
This question targets practical, hands-on experience with React.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
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.
Pro Tip
This topic has React.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.
Previous
What is the difference between useState and useReducer?
Next
What is React Concurrent Mode?