ReactMedium

What is useLayoutEffect?

useLayoutEffect has the same API as useEffect, but it runs synchronously after React updates the DOM and before the browser paints. Use it for reading layout (sizes, positions) and making a change that must be visible in the same frame, such as positioning a tooltip, to avoid flicker. It blocks painting, so use it sparingly.

Typical uses

  • Measure an element (getBoundingClientRect) and position a tooltip, popover or dropdown.
  • Adjust scroll position before the user sees the update (keep a chat scrolled to the bottom).
  • Synchronously sync layout-dependent state, such as whether text overflows.

Timing

  1. React renders and commits DOM changes.
  2. useLayoutEffect callbacks run (state updates here re-render synchronously before paint).
  3. The browser paints.
  4. useEffect callbacks run.

Costs

  • Blocks the paint, so slow code here delays what the user sees.
  • On the server it does nothing (there is no layout). React no longer warns about this since React 19, but the effect only runs on the client, so make the first render correct without it.

Alternatives

  • CSS solves many layout needs (position: sticky, container queries, anchor positioning).
  • Floating UI handles tooltip and popover positioning, including collision detection.
  • useInsertionEffect is for CSS-in-JS libraries injecting styles before layout effects; app code rarely needs it.
  • Fragment refs (React 19.3) can measure a group of children with getClientRects() without a wrapper.

Code example

tsx
1import { useLayoutEffect, useRef, useState } from "react";
2
3export function Tooltip({ anchorRect, text }: { anchorRect: DOMRect; text: string }) {
4 const ref = useRef<HTMLDivElement>(null);
5 const [top, setTop] = useState(0);
6
7 useLayoutEffect(() => {
8 // Measure before paint, so the tooltip never flashes in the wrong spot
9 const height = ref.current!.getBoundingClientRect().height;
10 const above = anchorRect.top - height - 8;
11 setTop(above > 0 ? above : anchorRect.bottom + 8); // flip below if no room above
12 }, [anchorRect]);
13
14 return (
15 <div
16 ref={ref}
17 role="tooltip"
18 style={{ position: "fixed", left: anchorRect.left, top, background: "#111", color: "#fff", padding: 6 }}
19 >
20 {text}
21 </div>
22 );
23}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app