Trivia Questions1 min readPremium

useEffect vs useLayoutEffect

Both hooks run side effects after React commits changes to the DOM. The difference is timing relative to the browser painting the screen, and that difference decides whether users see flicker. The React docs for useEffect and useLayoutEffect spell out the useEffect vs useLayoutEffect timing.

1. The commit timeline

render -> commit DOM mutations
       -> useLayoutEffect callbacks (synchronous, before paint)
       -> browser paints
       -> useEffect callbacks (asynchronous, after paint)

2. useEffect

  • Runs after the browser has painted.
  • Does not block the visual update, so it is the right default for data fetching, subscriptions, logging, timers, and syncing with external systems.
  • If it sets state that changes layout, the user may briefly see the “before” state (a flicker).

3. useLayoutEffect

  • Runs synchronously after DOM mutations but before paint.
  • Any state update inside it is processed before the browser paints, so the user only sees the final result.
  • Because it blocks painting, slow work here directly hurts responsiveness.

4. The classic use case: measure then position

function Tooltip({ anchorRect, children }) {
  const ref = useRef(null);
  const [top, setTop] = useState(0);

  useLayoutEffect(() => {
    const { height } = ref.current.getBoundingClientRect();
    setTop(anchorRect.top - height - 8); // applied before paint, no jump
  }, [anchorRect]);

  return <div ref={ref} style={{ position: 'fixed', top }}>{children}</div>;
}

With useEffect, the tooltip would paint at top: 0 first and then jump.

5. Server rendering

Neither effect runs on the server. useLayoutEffect historically logged a warning during SSR because its purpose (reading layout) is meaningless without a DOM. Libraries often use an “isomorphic” helper that picks useLayoutEffect in the browser and useEffect on the server.

6. Cleanup and ordering

  • Both return an optional cleanup that runs before the next effect run and on unmount.
  • Within a commit, all layout effects run before any passive (useEffect) effects.

Choosing: useEffect vs useLayoutEffect

Need Hook
Fetch data, subscribe, log analytics useEffect
Read layout (size/position) and synchronously re-render useLayoutEffect
Imperatively scroll or focus before the user sees the frame useLayoutEffect
Not sure Start with useEffect; switch only if you see flicker