What is useLayoutEffect and how does it differ from useEffect?

useLayoutEffect has the exact same signature as useEffect, but it differs crucially in when it fires during the React render cycle.

The Timing Difference:

  • useEffect (Asynchronous): Fires after React has updated the DOM, and after the browser has painted those changes to the screen. It is non-blocking, ensuring your app stays fast and responsive. Use this 99% of the time.
  • useLayoutEffect (Synchronous): Fires after React has updated the DOM, but BEFORE the browser has a chance to paint those changes to the screen. React will wait for your code inside useLayoutEffect to finish running before the user sees anything.

When to use useLayoutEffect:

You should only use it when you need to read layout measurements from the DOM (e.g., getting an element's height, width, or scroll position) and then immediately trigger a synchronous re-render to adjust the UI. Using useEffect for this causes a visible "flicker" because the user sees the initial paint, and then the corrected paint.

Code example

tsx
1import React, { useState, useLayoutEffect, useRef } from 'react';
2
3export default function TooltipFlickerFix() {
4 const [show, setShow] = useState(false);
5 const [tooltipHeight, setTooltipHeight] = useState(0);
6 const tooltipRef = useRef(null);
7
8 // 🚨 If this were useEffect, you would see a visible FLICKER.
9 // The tooltip would render at Y=0, the browser would paint it,
10 // THEN the effect would run, set the height, and it would jump up.
11 //
12 // ✅ With useLayoutEffect, it measures the DOM and updates the height
13 // BEFORE the browser ever paints to the screen. No flicker!
14 useLayoutEffect(() => {
15 if (show && tooltipRef.current) {
16 const { height } = tooltipRef.current.getBoundingClientRect();
17 setTooltipHeight(height);
18 }
19 }, [show]);
20
21 return (
22 <div className="p-12 flex justify-center items-center h-64">
23 <div className="relative inline-block">
24 <button
25 onMouseEnter={() => setShow(true)}
26 onMouseLeave={() => setShow(false)}
27 className="bg-blue-600 text-white px-6 py-3 rounded-lg shadow-lg font-bold hover:bg-blue-700 transition"
28 >
29 Hover over me
30 </button>
31
32 {show && (
33 <div
34 ref={tooltipRef}
35 // We dynamically adjust the top position based on its own measured height
36 style={{ top: `-${tooltipHeight + 10}px` }}
37 className="absolute left-0 w-48 p-3 bg-gray-900 text-white text-sm rounded-lg shadow-xl"
38 >
39 This tooltip measures its own height perfectly before you ever see it!
40 </div>
41 )}
42 </div>
43 </div>
44 );
45}

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 Hooks set.

Open in study app