React / 86
useLayoutEffect: measure before paint
Same shape as useEffect, but it runs after React updates the DOM and before the browser paints. Use it only to measure layout and fix it before the user sees a jump.
The timing
useEffect
may paint the first guess
- renderTooltip renders with height 0 (a guess)
- commitReact puts it in the DOM
- paintThe browser can paint it in the wrong spot
- effectMeasure the height, set state
- paintRe-render and paint the right spot. It jumped.
useLayoutEffect
measures before the first paint
- renderTooltip renders with height 0 (a guess)
- commitReact puts it in the DOM
- layoutMeasure the height, set state. Paint waits.
- renderRe-render straight away with the real height
- paintThe first paint is already right. No jump.
useLayoutEffect has exactly the same shape as useEffect: a setup function, an optional cleanup, a dependency array. The only difference is when it runs:
Render
React calls your component and gets JSX.Commit
React updates the DOM. Refs are filled in.Layout effects
useLayoutEffectruns. You can read sizes and positions. If you set state here, React re-renders straight away, still before painting.Paint
The browser draws the screen.Effects
useEffectusually runs now, after the user can already see the result.
The one-frame jump, slowed down
Try ituseEffectwaiting…
useLayoutEffectwaiting…
Example: a tooltip that picks a side
import { useLayoutEffect, useRef, useState } from "react";
export default function Tooltip({ targetRect, children }) {
const ref = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
setHeight(ref.current.getBoundingClientRect().height);
}, []);
const fitsAbove = targetRect.top - height >= 0;
const top = fitsAbove ? targetRect.top - height : targetRect.bottom;
return (
<div ref={ref} style={{ position: "fixed", left: targetRect.left, top }}>
{children}
</div>
);
}The first render uses height 0. The layout effect measures the real height and sets state. React re-renders with the right top before the browser paints, so the user only ever sees the final position. targetRect is the button's getBoundingClientRect(), measured by the parent.
useEffect is still the default
Don't
Use it everywhere 'to be safe'
useLayoutEffect(() => {
fetch(`/api/orders/${id}`).then(/* … */);
}, [id]);Nothing here touches layout, so blocking the paint only makes the page feel slower.
Do
Use it only to measure and adjust
useEffect(() => {
fetch(`/api/orders/${id}`).then(/* … */);
}, [id]);Fetching, subscriptions, logging and timers all belong in useEffect.
A good test: would the user see a flicker without it? If not, use useEffect.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
