ReactMedium

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

useEffectuseLayoutEffect
Timingafter paintafter DOM mutation, before paint
Blocks renderingnoyes
Visual flicker riskpossible for layout changesavoided
Server renderingdoes not rundoes not run
Typical usefetching, subscriptions, logging, timersmeasuring, 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

tsx
1import { useEffect, useLayoutEffect, useRef, useState } from "react";
2
3function 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 runtime
7 hook(() => {
8 setWidth(ref.current!.offsetWidth);
9 }, []);
10 return [ref, width] as const;
11}
12
13export function FlickerDemo() {
14 // With useEffect the first paint shows width 0, then updates: a flash
15 const [refA, widthA] = useMeasuredWidth(false);
16 // With useLayoutEffect the first paint already shows the right width
17 const [refB, widthB] = useMeasuredWidth(true);
18
19 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.

Open in study app