React Reference ยท Effect and Ref Hooks
React useLayoutEffect hook
Reference for React useLayoutEffect: measure and adjust the DOM synchronously before the browser paints, how it differs from useEffect, and SSR caveats.
useLayoutEffect has the same signature as useEffect, but it fires synchronously after React has changed the DOM and before the browser paints. Inside it you can read layout (sizes, positions) and, if needed, update state; React re-renders immediately, so the user never sees the intermediate frame.
Use it only when an effect has to measure something and the result changes what is drawn, such as positioning a tooltip next to its anchor or preserving scroll position. For everything else, useEffect is better because it does not block painting.
useLayoutEffect(() => { const { height } = ref.current.getBoundingClientRect(); setHeight(height); }, []);
Try it
The console shows the order for each update: render, layout cleanup, layout effect, then effect cleanup and effect.
In the browser this prints box has a real height and the user never sees measuring..., because the state update re-renders before paint.
Syntax
useLayoutEffect(setup, dependencies?)
function useLayoutEffect( setup: () => void | (() => void), dependencies?: ReadonlyArray<unknown> ): void;
| Name | Description |
|---|---|
setup |
Runs after DOM mutations and before paint. May return a cleanup function. |
dependencies |
Same rules as the useEffect dependency array. |
Returns: nothing.
Edge cases: it never executes during server rendering, so the first HTML cannot depend on it.
Usage notes
- It blocks painting. Slow code here delays every frame; keep it tiny and do heavy work elsewhere.
- State updates inside cause a second synchronous render before the browser paints. That is intended, but it costs time.
- Typical uses: tooltips and popovers that flip to stay in view, auto-growing textareas, restoring scroll position, measuring text for virtualized lists.
- Pitfall: moving visual logic to
useEffectcauses a visible flicker, one frame in the wrong place. That is the signal to switch touseLayoutEffect. - Server rendering: since layout effects never run on the server, render a sensible default and let the effect adjust on the client. Avoid needing the measured value to match the server HTML.
- Order: all layout cleanups, then all layout effects, run before any passive (
useEffect) cleanups and effects of the same commit. - For styling libraries,
useInsertionEffectruns even earlier.