Measuring layout before paint
Sometimes the size of an element decides what you render. You measure a box, then
show its width. useEffect is too late for that: it runs after the browser
has painted, so people see the first paint and then a flash as your correction
lands.
useLayoutEffect has the same shape, but React runs it after the DOM updates
and before the browser paints:
useLayoutEffect(() => {
const { width } = boxRef.current.getBoundingClientRect();
setWidth(width);
}, []);
Your state update happens before paint, so React re-renders and commits the corrected layout in the same frame. No one ever sees the intermediate state.
Reach for useLayoutEffect only when you must read layout — an element's size or
position — and render something from it. It blocks paint while it runs, so keep
it cheap. For everything else, useEffect is the right tool.
Your job is to measure a box in App.jsx and render its width.
Challenge
A box has to be measured before the browser paints, or its width flashes in a
frame late. Export an App component from App.jsx that renders a
<div data-testid="box"> and measures its width with useLayoutEffect. Store
the width in state and render it in a <p data-testid="width">.
The Test stubs getBoundingClientRect to report a width of 120, renders your
component, and expects the paragraph to read 120. The starter renders a fixed
0 and never measures, so the Test fails.