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

flushSync with DOM Measurements

See the pattern of updating state, using flushSync, then reading DOM dimensions or positions that depend on the new render.

flushSync with DOM Measurements

What you'll learn: How to use flushSync to force a render so you can immediately measure the updated DOM dimensions or positions.

The Common Pattern

Sometimes you need to update state and then measure something in the DOM that depends on that new state—all within the same event handler. For example, you might add an item to a list and need to scroll it into view, or you might update content and need to measure the new height for an animation.

Without flushSync, React batches your state update, meaning the DOM doesn't update until after your function finishes. If you try to measure the DOM immediately after setState, you'll get old measurements based on the previous render.

The Solution: flushSync → Measure

Here's the pattern:

import { flushSync } from 'react-dom';

function handleAddItem() {
  // Force this update to apply to the DOM immediately
  flushSync(() => {
    setItems([...items, newItem]);
  });
  
  // NOW the DOM reflects the new item
  const element = document.getElementById('new-item');
  const height = element.offsetHeight; // Accurate measurement
  const rect = element.getBoundingClientRect(); // Current position
  
  // Use these measurements for scrolling, animations, etc.
  element.scrollIntoView();
}

Why This Works

flushSync forces React to render and commit immediately, so by the time the next line runs, the DOM has been updated. Your measurements reflect the new state, not the old snapshot.

This is common when implementing scroll-to-bottom chat interfaces, auto-expanding text areas, or any animation that needs to know the "before" and "after" sizes.

Key Takeaway: Use flushSync before DOM measurements when you need dimensions or positions that depend on state you just updated—it guarantees the DOM is fresh before you measure it.