Difference: useEffect vs useLayoutEffect?
Both run after React commits DOM changes, but useEffect runs after the browser paints (non-blocking), while useLayoutEffect runs before paint (blocking). Use useEffect by default; use useLayoutEffect only when you must measure or change layout before the user sees the frame.
Comparison
useEffect | useLayoutEffect | |
|---|---|---|
| Timing | after paint | after DOM mutation, before paint |
| Blocks rendering | no | yes |
| Visual flicker risk | possible for layout changes | avoided |
| Server rendering | does not run | does not run |
| Typical use | fetching, subscriptions, logging, timers | measuring, positioning, scroll adjustments |
Example of the difference
A tooltip positioned in useEffect first paints at a default position, then jumps: a visible flicker. In useLayoutEffect, measurement and correction happen before paint, so the user sees only the final position.
Performance
Work in useLayoutEffect delays every frame it runs in. Keep it small, avoid network calls there, and prefer CSS solutions.
Order of execution
On each commit: DOM updates, refs attached, layout effect cleanups and setups, paint, then passive effect cleanups and setups. Cleanups always run before the next setup of the same effect.
Rule of thumb
"Does the user see something wrong for one frame if I use useEffect?" If yes, use useLayoutEffect. If no, useEffect.
Code example
1import { useEffect, useLayoutEffect, useRef, useState } from "react";23function useMeasuredWidth(useLayout: boolean) {4 const ref = useRef<HTMLDivElement>(null);5 const [width, setWidth] = useState(0);6 const hook = useLayout ? useLayoutEffect : useEffect; // demo only: never switch hooks at runtime7 hook(() => {8 setWidth(ref.current!.offsetWidth);9 }, []);10 return [ref, width] as const;11}1213export function FlickerDemo() {14 // With useEffect the first paint shows width 0, then updates: a flash15 const [refA, widthA] = useMeasuredWidth(false);16 // With useLayoutEffect the first paint already shows the right width17 const [refB, widthB] = useMeasuredWidth(true);1819 return (20 <>21 <div ref={refA}>useEffect width: {widthA}px</div>22 <div ref={refB}>useLayoutEffect width: {widthB}px</div>23 </>24 );25}
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.