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

The flushSync Syntax and Import

Understand how to import flushSync from react-dom and wrap state updates to trigger immediate synchronous rendering.

The flushSync Syntax and Import

You'll learn: How to import and use flushSync to force React to apply state updates synchronously, bypassing automatic batching.

While flushSync breaks React's usual batching behavior (as you learned in the previous lesson), actually using it requires knowing the correct syntax and import statement.

Importing flushSync

flushSync comes from the react-dom package, not the main react package:

import { flushSync } from 'react-dom';

Notice it's react-dom, not react. This is because flushSync forces immediate DOM updates, which is a DOM-specific operation.

The Basic Syntax

Wrap the state update(s) you want to flush immediately inside flushSync:

import { useState } from 'react';
import { flushSync } from 'react-dom';

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    flushSync(() => {
      setCount(count + 1);
    });
    // By this line, the DOM has been updated
    console.log('DOM updated, count is now:', count + 1);
  }

  return <button onClick={handleClick}>{count}</button>;
}

The callback you pass to flushSync executes immediately, and React commits those changes to the DOM before moving to the next line of code.

Multiple Updates

You can batch multiple updates inside one flushSync call:

flushSync(() => {
  setName('Alice');
  setAge(30);
});
// Both updates committed to DOM here

But separate flushSync calls trigger separate re-renders, defeating batching's performance benefits.

Key Takeaway: Import flushSync from 'react-dom' and wrap state updates in flushSync(() => { ... }) to force immediate, synchronous rendering — use sparingly as it bypasses React's optimized batching.