Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React useLayoutEffect vs useEffect: Synchronous DOM Measurements and Flicker Fixes

One hook runs before the browser paints and one after. Measuring layout in the wrong one costs a visible frame of flicker on every mount.

~5 min readReact
#React#Hooks#Rendering
3D illustration of a browser paint timeline with a synchronous layout measurement step running before the frame is presented

Quick Summary

Both hooks run after React has committed DOM changes, but only one of them runs before the browser paints. useEffect is scheduled after paint, which keeps rendering responsive; useLayoutEffect runs synchronously in the same commit, blocking paint until it returns. The difference is invisible for data fetching and visible for measurements: any state derived from getBoundingClientRect, scrollHeight, or an element's size must be applied in useLayoutEffect, or the browser paints the wrong layout first and the user sees a flicker.

The rule most teams adopt is mechanical. If the effect reads layout or writes layout that the user would otherwise see move, use useLayoutEffect. If it talks to the network, subscribes to a global event, or does anything that does not need to be finished before the next frame, use useEffect.

The cost of useLayoutEffect is real. It blocks the browser from painting, it runs twice on mount in StrictMode, and it forces synchronous layout when it reads geometry right after a DOM mutation. Reaching for it to "make things faster" has the opposite effect; reaching for it to place a tooltip before the first paint is exactly right.

Basic Syntax & Signature

tsx
import { useEffect, useLayoutEffect, useRef, useState } from "react"; function Tooltip({ text, anchor }: { text: string; anchor: DOMRect }) { const ref = useRef<HTMLDivElement>(null); const [left, setLeft] = useState(anchor.left); // Runs after DOM mutation, before paint: the clamp is already applied // when the frame is presented, so the tooltip never appears off-screen. useLayoutEffect(() => { const el = ref.current; if (!el) return; const { width } = el.getBoundingClientRect(); const max = window.innerWidth - 8 - width; setLeft(Math.min(Math.max(8, anchor.left), max)); }, [anchor.left, text]); return ( <div ref={ref} style={{ position: "fixed", top: anchor.bottom, left }}> {text} </div> ); } function Analytics({ page }: { page: string }) { // Runs after paint: a network call or a log must not block the frame. useEffect(() => { void fetch("/api/pageview", { method: "POST", body: JSON.stringify({ page }) }); }, [page]); return null; }

Ordering inside a commit is fixed: React mutates the DOM, runs useLayoutEffect cleanups, runs useLayoutEffect setups, then the browser paints, then useEffect runs. Passive effects are flushed in a separate task, which is why a setState inside useEffect costs an extra paint that useLayoutEffect avoids.

tsx
// Cleanup order on dependency change: // 1. useLayoutEffect cleanup (previous deps) // 2. useLayoutEffect setup (new deps) // 3. paint // 4. useEffect cleanup (previous deps) // 5. useEffect setup (new deps)

On unmount, layout cleanups run before passive cleanups for the same subtree, so a listener added in useEffect can outlive a layout effect's teardown by one frame.

Key Comparison Table

PropertyuseEffectuseLayoutEffect
TimingAfter paint, in a separate taskBefore paint, synchronously in the commit
Blocks the browserNoYes, until it returns
Reads layout safelyYes, but after the frame is shownYes, while the frame can still be corrected
setState causesSecond render and second paintSecond render before the first paint
Visible flickerPossiblePrevented
Server renderingRuns on the client after hydrationWarns and does nothing; no DOM on the server
StrictMode double invokeYes, in developmentYes, in development
Typical useFetching, subscriptions, logging, timersMeasurement, scroll position, focus, tooltips
Cost when misusedSlight delayJank: a long task on every commit
Order relative to paintAfterBefore

Practical Edge Cases & Deep Dives

1. The flicker that only useLayoutEffect removes

tsx
function BadMeasure() { const ref = useRef<HTMLParagraphElement>(null); const [clamped, setClamped] = useState(false); useEffect(() => { const el = ref.current; if (el) setClamped(el.scrollHeight > el.clientHeight); }, []); return ( <p ref={ref} style={{ height: 40, overflow: "hidden" }}> Long text that overflows the fixed height and should show a "Read more" button. {clamped && <button>Read more</button>} </p> ); }

With useEffect the browser paints the paragraph without the button and then repaints with it — a one-frame layout shift that is easy to see on a slow device and shows up as a cumulative layout shift score in the field data. Replacing the hook with useLayoutEffect keeps the first paint correct because the state is committed before the frame is presented. If the measurement itself is expensive, gates matter more than the hook: measure once, store the result, and re-measure from a ResizeObserver instead of on every render.

2. Scrolling a chat log to the bottom

tsx
function Chat({ messages }: { messages: string[] }) { const listRef = useRef<HTMLDivElement>(null); useLayoutEffect(() => { const el = listRef.current; if (!el) return; // scrollHeight is only correct after the new message is in the DOM, // and scrolling after paint would show the jump for one frame. el.scrollTop = el.scrollHeight; }, [messages.length]); return ( <div ref={listRef} style={{ overflowY: "auto", height: 320 }}> {messages.map((m, i) => <p key={i}>{m}</p>)} </div> ); }

The dependency is messages.length, not messages: an array recreated on each parent render would scroll the log on unrelated updates. If messages arrive while the user has scrolled up, the correct behaviour is to skip the scroll — track distance from the bottom before the mutation and restore only when it was near zero.

3. Measuring before setup, without a layout round trip

tsx
function AutoSizedTextarea({ value }: { value: string }) { const ref = useRef<HTMLTextAreaElement>(null); useLayoutEffect(() => { const el = ref.current; if (!el) return; // Reset first: scrollHeight only shrinks after the height is cleared. el.style.height = "auto"; el.style.height = `${el.scrollHeight}px`; }, [value]); return <textarea ref={ref} rows={1} defaultValue={value} />; }

This is the one place where a layout write inside a layout effect is unavoidable: the height depends on content that only the browser can measure. Reading scrollHeight and writing height in the same block causes one forced synchronous layout, which is cheaper than a visible resize.

4. An SSR-safe isomorphic hook

tsx
import { useEffect, useLayoutEffect } from "react"; // useLayoutEffect does nothing on the server and logs a warning. // Falling back keeps Next.js and other SSR frameworks quiet. export const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect; function ScrollProgress() { const [progress, setProgress] = useState(0); useIsomorphicLayoutEffect(() => { function onScroll() { const max = document.documentElement.scrollHeight - window.innerHeight; setProgress(max > 0 ? window.scrollY / max : 0); } onScroll(); window.addEventListener("scroll", onScroll, { passive: true }); return () => window.removeEventListener("scroll", onScroll); }, []); return <div style={{ width: `${progress * 100}%`, height: 2 }} />; }

The alternative is to avoid the layout effect on the server entirely by rendering the component only on the client. Both work; the first keeps the component usable in static output and degrades to a post-paint update, which is acceptable for a progress bar and not acceptable for a tooltip position.

5. Observing size instead of measuring on every render

tsx
function useElementWidth<T extends HTMLElement>() { const ref = useRef<T>(null); const [width, setWidth] = useState(0); useLayoutEffect(() => { const el = ref.current; if (!el) return; const rect = el.getBoundingClientRect(); setWidth(rect.width); const observer = new ResizeObserver((entries) => { for (const entry of entries) { setWidth(entry.contentRect.width); } }); observer.observe(el); return () => observer.disconnect(); }, []); return [ref, width] as const; }

ResizeObserver callbacks arrive before paint in the same frame, which gives the correctness of a layout effect with far fewer reads: one measurement on mount, then one per actual resize. Combining this with useSyncExternalStore keeps the subscription outside React's render path.

6. What runs twice in StrictMode

tsx
function Counter() { const ref = useRef<HTMLDivElement>(null); console.log("render"); useLayoutEffect(() => { console.log("layout setup", ref.current?.getBoundingClientRect().height); return () => console.log("layout cleanup"); }, []); useEffect(() => { console.log("passive setup"); return () => console.log("passive cleanup"); }, []); return <div ref={ref}>height probe</div>; }

In development with StrictMode, React renders twice, then mounts, runs the effects, unmounts the simulated instance (running cleanups), and mounts again. The log sequence shows render render, layout setup, layout cleanup, layout setup, passive setup, passive cleanup, passive setup. Effects that are not idempotent — starting a poller, incrementing a counter ref, subscribing without unsubscribing — surface here first.

Common Compilation/Runtime Mistakes

SymptomCauseFix
"useLayoutEffect does nothing on the server" warningHook used during SSRIsomorphic wrapper or client-only render
Tooltip appears, then jumps into placeMeasured in useEffectMove the measurement to useLayoutEffect
Visible one-frame layout shift on loadState applied after paintApply before paint, or reserve space with CSS
Page hangs for 200 ms on route changeHeavy work in useLayoutEffectMove it to useEffect or off the main thread
Effect fires on every renderUnstable dependency objectDepend on primitives or memoize
Listener leak in developmentSubscription without cleanupReturn a cleanup function
Infinite loopLayout effect sets state it depends onRemove state as a dependency; derive instead
Multiple forced reflows in a profileReading and writing layout repeatedlyBatch reads first, then writes
Scroll position resets after navigationScroll written in a layout effect on re-renderGuard with a key or scrollRestoration
Warnings about missing dependenciesDeliberate omissionRestructure the effect so the dependency is stable

The decision rule is narrow enough to keep in a code-review checklist: layout effects exist so that the frame is correct the first time it is presented. If the effect's output can wait for the next frame — a log, a request, a timer — it belongs in useEffect, where it costs nothing to the frame budget.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.