Sub topic 16
useLayoutEffect and when timing matters
This chapter assumes you know useEffect, dependency arrays and cleanup functions from the earlier chapters. It also assumes you know the render and commit cycle. Here you will learn the one hook that runs at a different moment than useEffect. You will also learn the narrow set of cases where that difference matters.
Where each hook runs
React updates the screen in phases. It first calls your component to compute what the UI should look like (render). It then applies the changes to the DOM (commit). After that, the browser paints pixels.
useEffect runs after the browser has had a chance to paint. useLayoutEffect runs earlier. It runs right after React updates the DOM and before the browser paints. Its signature, dependency array and cleanup behavior are identical to useEffect.
Two properties follow from this order:
- Inside a layout effect, the DOM already reflects the new render, so you can measure it.
- If a layout effect sets state, React re-renders synchronously before the browser paints. The user never sees the intermediate frame.
A layout effect also blocks painting while it runs. Slow work in a layout effect delays what the user sees.
The problem it solves: a visible flicker
Suppose a tooltip must sit above its anchor. Its position depends on its own height, which you only know after it is in the DOM. With useEffect, the sequence can look like this:
- React renders the tooltip at a default position.
- The browser paints it there.
- The effect measures the height and sets state.
- React re-renders and the tooltip jumps to the correct position.
The user may see one frame with the tooltip in the wrong place. With useLayoutEffect, steps 3 and 4 happen before the first paint, so only the correct position is ever shown.
import { useLayoutEffect, useRef, useState } from 'react';
function Tooltip({ anchorRect, children }) {
const ref = useRef(null);
const [top, setTop] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTop(anchorRect.top - height - 8);
}, [anchorRect]);
return (
<div ref={ref} style={{ position: 'fixed', left: anchorRect.left, top }}>
{children}
</div>
);
}
export default function App() {
const [rect, setRect] = useState(null);
return (
<div style={{ padding: 100 }}>
<button onClick={(e) => setRect(e.currentTarget.getBoundingClientRect())}>
Show tip
</button>
{rect && <Tooltip anchorRect={rect}>Saved!</Tooltip>}
</div>
);
}The layout effect reads getBoundingClientRect(), which forces the browser to compute layout. That read is only reliable after the DOM has been updated, and the layout effect guarantees this. Setting top triggers a second render, but it happens before paint.
Choosing between the two hooks
Start with useEffect. Switch only when you can name a visible problem that earlier timing fixes.
| Question | useEffect | useLayoutEffect |
|---|---|---|
| Runs relative to paint | Usually after | Before |
| Blocks the browser from painting | No | Yes, while the callback runs |
| DOM is already updated | Yes | Yes |
| Typical use | Fetching, subscriptions, timers, logging | Measuring layout, positioning, preventing flicker |
| Runs on the server | Never | Never |
| Cost of slow code | Delayed side effect | Delayed frame |
Good reasons to use a layout effect:
- Measuring an element's size or position and adjusting the UI immediately, as with tooltips, popovers and dropdown placement.
- Restoring or setting scroll position after content changes, for example keeping a chat list scrolled to the bottom.
- Synchronously reading layout and then writing to the DOM so the two stay consistent.
Poor reasons to use one:
- Data fetching, analytics, or subscriptions. None of these affect the first painted frame.
- "It feels faster." A layout effect delays paint, so it can only make a slow callback feel worse.
- Fixing a bug you have not diagnosed. If an effect reads stale values, the cause is the dependency array, not timing.
Timing is not a guarantee for useEffect
Do not treat "after paint" as a promise. React may run a useEffect callback earlier than you expect. For example, React flushes pending effects before it starts the next render. Updates caused by discrete events such as clicks can also run their effects before the browser paints.
Do not build correctness on this ordering. If your code only works when an effect runs after paint, or only when it runs before, something is wrong. Use useLayoutEffect when you need the guarantee that the callback runs before paint. Otherwise write the effect so its timing does not matter.
Cleanup and ordering
Layout effects follow the same lifecycle rules as other effects. The cleanup of the previous run executes before the next run, and again on unmount. React also runs all layout effect cleanups and callbacks for an update before it runs the passive effects of that update.
The following hook measures an element and keeps the measurement current with a ResizeObserver:
import { useLayoutEffect, useRef, useState } from 'react';
function useElementHeight() {
const ref = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
const node = ref.current;
if (!node) return;
setHeight(node.getBoundingClientRect().height);
const observer = new ResizeObserver(([entry]) => {
setHeight(entry.contentRect.height);
});
observer.observe(node);
return () => observer.disconnect();
}, []);
return [ref, height];
}
export default function Panel() {
const [ref, height] = useElementHeight();
return (
<div ref={ref}>
<p>This panel is {Math.round(height)}px tall.</p>
</div>
);
}The first measurement happens before paint, so the text never shows 0px. The observer handles later size changes. The cleanup disconnects it, which also keeps the hook safe under Strict Mode's development re-run.
Server rendering
Effects never run during server-side rendering, because the server produces HTML and has no DOM to commit to. Older React versions print a warning when they see useLayoutEffect on the server, because the layout effect cannot prevent a flicker in HTML that was generated before any client code ran. React 19 removed that warning, but the underlying fact is unchanged. If the first paint comes from server HTML, a layout effect cannot correct it before that paint.
If you must support both environments in a library or shared hook, a common pattern picks the hook by environment:
import { useEffect, useLayoutEffect } from 'react';
const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect;For measurement-dependent UI in a server-rendered app, a more reliable design is to render a neutral placeholder first, such as hidden content. The client then measures and reveals the content after hydration.
Common mistakes
- Doing slow work in a layout effect. Loops over large lists or expensive calculations block painting. Move them into render with
useMemoor intouseEffect. - Setting state in a layout effect on every run. This causes a synchronous second render each time. Without a correct dependency array it can loop forever.
- Reading layout and writing layout repeatedly. Alternating reads such as
getBoundingClientRect()with style writes forces the browser to recompute layout each time. Batch all reads first, then all writes. - Using it to avoid understanding dependencies. Changing the hook does not fix stale closures or unstable dependencies.
Summary of the decision
- Can the value be computed during render? Do that and skip effects entirely.
- Is the work a side effect that does not affect the first painted frame? Use
useEffect. - Does the work read layout and the user would see a wrong frame otherwise? Use
useLayoutEffect, keep it small, and handle the server case.
Exercise
A dropdown menu renders below its button. A useEffect measures the menu and, if it would overflow the viewport, sets state to flip it above the button. Users report a brief flash of the menu in the wrong place. Which hook should replace useEffect, and why does it remove the flash?
Show answer
Replace it with useLayoutEffect. The layout effect runs after React updates the DOM but before the browser paints. The measurement and the state update that flips the menu happen, and React re-renders synchronously, before the first paint. The user only ever sees the corrected position.
Exercise
A teammate changes an analytics call that logs a page view from useEffect to useLayoutEffect "so it runs sooner". Is this a good change? Give two reasons.
Show answer
No. First, the analytics call does not affect what is painted, so running before paint gains nothing visible. Second, a layout effect blocks painting while it runs, so any slowness in the call delays the frame. The call also never runs on the server either way, so the change gives no benefit there. useEffect is the right choice.