Q34: What is flushSync and when should you use it?

flushSync forces React to flush all pending state updates synchronously and update the real DOM immediately. Use it sparingly when you must read updated DOM measurements (like scroll positions) immediately after updating state.

Forcing Immediate Synchronous DOM Commit
import { flushSync } from 'react-dom';

const handleClick = () => {
  // Force immediate synchronous DOM commit
  flushSync(() => {
    setCount(count + 1);
  });
  // DOM is updated synchronously now
  console.log('Scroll Height:', divRef.current.scrollHeight);
};
💡 flushSync forces React to commit state updates to real DOM elements before executing subsequent code lines.
Key Takeaways
  • Forces immediate synchronous state processing and DOM commits.
  • Bypasses automatic batching; degrades rendering performance if overused.
Knowledge Check

What operational downside occurs when frequently calling flushSync?