useLayoutEffect: Pre-Paint Synchronous Effects
What you'll learn: When and why to use useLayoutEffect for DOM measurements or mutations that must happen before the browser paints.
The Timing Problem
You've learned that useEffect runs after the browser paints the screen. This is usually perfect — your side effects don't block visual updates. But sometimes you need to read or change the DOM before the user sees anything, to prevent visual flickers or incorrect layouts.
What useLayoutEffect Does
useLayoutEffect has the exact same API as useEffect, but it fires synchronously after React commits changes to the DOM, but before the browser paints. It blocks the paint until your effect completes.
Think of it like this: useEffect says "do this after the user sees the update," while useLayoutEffect says "do this before the user sees anything."
When to Use It
Use useLayoutEffect when you need to:
- Measure DOM nodes (scroll position, element dimensions) and immediately update state based on those measurements
- Mutate the DOM directly to prevent flicker (like positioning a tooltip)
- Synchronize with third-party libraries that need pre-paint access
useLayoutEffect(() => {
const height = divRef.current.offsetHeight;
setTooltipPosition(height + 10); // Must happen before paint
}, []);
If you used useEffect here, users might see the tooltip in the wrong position for a frame before it jumps.
The Cost
Because useLayoutEffect blocks painting, it can make your app feel sluggish if the effect takes too long. Always prefer useEffect unless you have a specific visual reason to run synchronously.
Key Takeaway: Use useLayoutEffect when you need to read from or write to the DOM before the browser paints, preventing visual flickers — but reach for useEffect by default for better performance.