useLayoutEffect: The Synchronous Alternative
What you'll learn: When to reach for useLayoutEffect to measure or mutate the DOM before the browser paints.
Why useLayoutEffect Exists
You just learned that useEffect runs after paint—the browser draws the screen first, then your effect code executes. This is perfect 99% of the time because it keeps the UI responsive.
But sometimes you need to read from or write to the DOM before the user sees anything. That's where useLayoutEffect comes in.
The Key Difference
useLayoutEffect has the exact same signature as useEffect:
useLayoutEffect(() => {
// Your effect code
return () => {
// Your cleanup
};
}, [dependencies]);
The difference? Timing.
useEffect: Render → Commit → Paint → EffectuseLayoutEffect: Render → Commit → Effect → Paint
useLayoutEffect runs synchronously after React updates the DOM but before the browser paints. This blocks painting until your effect completes.
When to Use It
Measuring DOM elements:
useLayoutEffect(() => {
const height = divRef.current.offsetHeight;
setTooltipPosition(height + 10);
}, []);
If you used useEffect here, the user would see the tooltip in the wrong position for a split second (visual flicker).
Mutating the DOM before paint: Adjusting scroll positions, animating elements into view, or positioning floating elements based on measurements.
When NOT to Use It
For everything else! Data fetching, logging, subscriptions—use useEffect. useLayoutEffect blocks painting, so it hurts performance if overused.
Key Takeaway: Use useLayoutEffect only when you need to measure or mutate the DOM before the browser paints to prevent visual flickers—otherwise stick with useEffect.