What is the useLayoutEffect hook and how does it differ from useEffect?
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".