What is the difference between useEffect and useLayoutEffect?
Hint
useEffect fires after paint; useLayoutEffect fires synchronously before paint — use for DOM measurements
Full Answer
Both run after render but at different times:
- useEffect — fires after the browser paints. Non-blocking. Use for most side effects (data fetching, subscriptions).
- useLayoutEffect — fires synchronously after DOM mutations but before paint. Blocking. Use for reading layout to prevent visual flicker.
// useEffect — paint happens first, then effect
// Causes flicker if you update DOM based on measurement
useEffect(() => {
const height = ref.current.offsetHeight; // reads layout
setHeight(height); // triggers second render → visible flicker!
}, []);
// useLayoutEffect — DOM updated, effect runs, THEN paint
// No flicker because browser hasn't painted yet
useLayoutEffect(() => {
const height = ref.current.offsetHeight;
setHeight(height); // only one paint with correct height
}, []);
Sequence:
render → DOM mutations → useLayoutEffect → browser paint → useEffect
💡 Prefer useEffect by default — it doesn't block the browser. Only switch to useLayoutEffect if you see visual flickers from DOM measurement/mutation. Also note: useLayoutEffect is skipped during SSR.
More Hooks Questions
Practice this in a timed sprint
5 free questions, no signup required