Skip to content

QuizNot attempted

Measuring the DOM before paint

Why is useLayoutEffect used here instead of useEffect?
function Tooltip() {
const ref = useRef(null);
const [top, setTop] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTop(height);
}, []);
return <div ref={ref} style={{ marginTop: top }}>box</div>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • useLayoutEffect runs synchronously after DOM mutations but before the browser paints, preventing a visible flicker when adjusting layout based on measured DOM size
  • useLayoutEffect runs after DOM mutations but before paint, so measuring and calling setTop re-renders synchronously and the user never sees the box in the wrong position.
  • Not 'runs before render': it runs after commit, like all effects.
  • Not 'no difference': with useEffect the first paint shows marginTop: 0, then a visible jump.
  • Not 'required with useRef': refs work with any effect.