Question presented to candidate:
"When is useLayoutEffect the right choice, and what does it cost you?"
What a strong answer should cover:
- Both run after React has committed changes to the DOM. The difference is relative to paint:
useLayoutEffectruns synchronously before the browser paints;useEffectruns asynchronously after. - The use case: measure the DOM and adjust it in the same frame, so the user never sees the intermediate state.
- Concrete cases: positioning a tooltip or popover from a measured rect, measuring text to decide truncation, restoring scroll position, and preventing a visible flash on a mount-time adjustment.
- The cost is real: it blocks painting. Slow work there delays the frame, and a long layout effect is directly visible as jank.
- It runs on every commit where its dependencies change, exactly like
useEffect. - It does not run during SSR — neither does
useEffect— but React warns specifically aboutuseLayoutEffecton the server because layout measurement is meaningless there. useInsertionEffectsits even earlier, for CSS-in-JS libraries injecting styles.- The default is
useEffect; reach for the layout variant only when you can name the flicker it prevents.
Clarifying questions expected:
- "Is there a visible flicker, or is this a habit?" — if nothing flashes,
useEffectis correct. - "Is this server-rendered?" — that changes what warns.
Code / implementation expected: Yes — a measure-then-position example where the difference is visible.