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

Alternatives to flushSync: Effect-Based Solutions

Learn when useLayoutEffect or refs provide better solutions than forcing synchronous updates with flushSync.

Alternatives to flushSync: Effect-Based Solutions

What you'll learn: When to skip flushSync and use useLayoutEffect or refs for cleaner, more React-idiomatic solutions.

The Problem with Reaching for flushSync

You've learned that flushSync forces synchronous updates, breaking React's batching for performance. But often, you don't actually need synchronous state updates—you just need to do something after the DOM has been updated. That's where effects and refs shine.

useLayoutEffect: The Synchronous Effect Alternative

useLayoutEffect runs after React commits to the DOM but before the browser paints. It's synchronous and blocking, making it perfect for DOM measurements or adjustments:

function ScrollToBottom() {
  const ref = useRef(null);

  useLayoutEffect(() => {
    // Runs after DOM update, before paint
    ref.current.scrollTop = ref.current.scrollHeight;
  });

  return <div ref={ref}>{/* content */}</div>;
}

Instead of forcing state to update synchronously with flushSync, let React update naturally and measure in useLayoutEffect. No batching interrupted, no performance hit.

Refs for Immediate DOM Access

Sometimes you don't even need state. If you're just storing a value to read later or manipulating the DOM directly, refs bypass the render cycle entirely:

const inputRef = useRef(null);

function focusInput() {
  inputRef.current.focus(); // Direct DOM manipulation, no state needed
}

When to Use What

  • useLayoutEffect: Need to measure or adjust the DOM after React updates it
  • useRef: Need to store values that don't trigger re-renders or access DOM nodes
  • flushSync: Last resort when you absolutely need to break batching (rare!)

Key Takeaway: Before reaching for flushSync, ask: "Do I need synchronous state, or just synchronous effects?" Most of the time, useLayoutEffect or refs solve the problem more elegantly without sacrificing React's batching performance.