Course contentsShow
← React
Lesson 444 of 2,39612. Rendering and BatchingFree lesson

What flushSync Does: Breaking Out of Batching

Learn how flushSync forces React to immediately process state updates and re-render synchronously instead of batching.

What flushSync Does: Breaking Out of Batching

You'll learn how to force React to immediately process state updates synchronously when batching won't work for your use case.

The Core Idea

By now you know that React batches multiple state updates together for performance — it waits until your event handler finishes, then renders once with all updates applied. But sometimes you need the DOM to update immediately before continuing your code. That's where flushSync comes in.

flushSync is React's escape hatch that says: "Stop batching. Process this state update right now and commit it to the DOM synchronously before moving on."

When You Might Need It

Imagine you're building a chat app where new messages should auto-scroll to the bottom. You add a message to state, then need to measure the scroll container's height to scroll it. If React batches the update, the DOM hasn't changed yet when you try to scroll — you're measuring the old height.

flushSync forces React through the entire render-commit cycle immediately:

import { flushSync } from 'react-dom';

function addMessage(newMessage) {
  flushSync(() => {
    setMessages(prev => [...prev, newMessage]);
  });
  // DOM is now updated — safe to measure/scroll
  scrollContainer.scrollTop = scrollContainer.scrollHeight;
}

The Trade-off

Using flushSync breaks batching's performance benefits. Each flushSync call triggers a full render-commit cycle immediately. Use it sparingly — only when you truly need synchronous DOM updates for measurements, third-party library integration, or focus management.

Key Takeaway: flushSync forces React to immediately process state updates and commit to the DOM synchronously, breaking out of automatic batching when you need guaranteed DOM changes before continuing execution.