What is the difference between useEffect and useLayoutEffect?
useEffect runs after the browser has painted. useLayoutEffect runs after DOM changes but before paint, and blocks painting. Use the layout version only to measure or adjust the DOM so users do not see a flicker.
Explain it simply
Picture a wedding hall. useEffect is the decorator who comes in after guests have already entered. useLayoutEffect is the one who finishes before the doors open, so nobody sees half-hung curtains.
Because it blocks painting, a slow layout effect makes the screen feel stuck. Prefer useEffect and switch only when you see a visible jump.
Example
function Tooltip({ text }) {
const ref = useRef(null);
const [top, setTop] = useState(0);
useLayoutEffect(() => {
setTop(ref.current.getBoundingClientRect().height); // measure before paint
}, [text]);
return <div ref={ref} style={{ marginTop: -top }}>{text}</div>;
}It does not run on the server, so it logs a warning in older server-rendered setups.
What to say in the interview
"Both run after render commits to the DOM, but useLayoutEffect fires synchronously before the browser paints, while useEffect fires after paint. I use useLayoutEffect for measuring and positioning, where a flash would be visible, and useEffect for everything else."
Common mistakes
- Using useLayoutEffect for data fetching, which delays the first paint for no reason.