What is the useLayoutEffect hook and how does it differ from useEffect?
Why Interviewers Ask This
This tests whether you can apply React.js knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Both useLayoutEffect and useEffect run after React has committed changes to the DOM. The difference is when. useEffect runs asynchronously after the browser has painted — the user sees the updated UI first, then the effect runs. useLayoutEffect runs synchronously after DOM mutations but before the browser paints — it fires at the same phase as componentDidMount/componentDidUpdate. React waits for useLayoutEffect to finish before letting the browser paint. When to use useLayoutEffect: when you need to read layout information from the DOM (element dimensions, scroll position) and then synchronously update the DOM or state before the browser paints — prevents a visual flash. Example: measuring an element's height to position a tooltip. Caution: useLayoutEffect blocks the browser from painting — if it does heavy work, it creates jank. Prefer useEffect for most cases. useLayoutEffect also causes SSR issues (server has no DOM) — use a guard: typeof window !== "undefined".
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.