React Hooks
React useLayoutEffect Hook
useLayoutEffect has the same signature as useEffect but runs synchronously after the DOM is mutated and before the browser paints. Use it only when you must measure layout and change it before the user sees the intermediate state.
What is useLayoutEffect Hook in React?
useLayoutEffect has the same signature as useEffect but runs synchronously after the DOM is mutated and before the browser paints. Use it only when you must measure layout and change it before the user sees the intermediate state.
Why useLayoutEffect Hook matters
Positioning a tooltip based on the trigger’s bounding box is the classic case: with useEffect the tooltip flashes in the wrong place for one frame; with useLayoutEffect the correction happens before paint.
useLayoutEffect Hook example
useLayoutEffect(() => {
const rect = tooltipRef.current.getBoundingClientRect();
if (rect.right > window.innerWidth) {
tooltipRef.current.style.left = `${window.innerWidth - rect.width - 8}px`;
}
}, [open]);useEffect vs useLayoutEffect
| useEffect | useLayoutEffect | |
|---|---|---|
| Timing | after paint, asynchronous | after DOM mutation, before paint |
| Blocks painting | no | yes |
| Use for | fetching, subscriptions, logging | measuring and correcting layout |
| Server rendering | fine | warns — it cannot run on the server |
Common mistakes with useLayoutEffect Hook
- Using it as the default — blocking paint on every render hurts perceived performance.
- Calling it in a server-rendered component, which logs a warning in Next.js and similar frameworks.
React useLayoutEffect Hook— Interview Questions & FAQs
When should I use useLayoutEffect instead of useEffect?+
Only when you read layout (getBoundingClientRect, scroll position) and immediately change it, and a one-frame flicker would be visible. Everything else belongs in useEffect.
