← Back to Articles         
useLayoutEffect - React Hook

useLayoutEffect - React Hook

Published on 15 Nov 2026 23 min read React
React Fundamentals

1. What is useLayoutEffect?

useLayoutEffect is a React Hook used to run code after React updates the DOM but before the browser paints the updated screen.

The key idea is:

React renders
     ↓
DOM is updated
     ↓
useLayoutEffect runs
     ↓
Browser paints the screen

This is different from useEffect:

React renders
     ↓
DOM is updated
     ↓
Browser paints the screen
     ↓
useEffect runs

So the most important difference is timing.

Simple definition

useLayoutEffect is mainly used when you need to read or change the DOM before the user sees the result.

Typical examples:

  • Measuring an element's width/height
  • Calculating an element's position
  • Positioning a tooltip
  • Adjusting scroll position
  • Preventing visible flickering
  • Working with third-party DOM libraries
  • Performing DOM-related calculations before painting

2. Why do we need useLayoutEffect?

Most of the time, you should use:

useEffect()

But sometimes timing matters.

Consider a tooltip.

You first render:

Button
   ↓
Tooltip

You need to calculate the button's position before deciding where to put the tooltip.

If you use useEffect, the browser may paint the initial incorrect position first:

Initial render
     ↓
Tooltip appears at wrong position
     ↓
Browser paints
     ↓
useEffect calculates position
     ↓
Tooltip moves to correct position

The user may briefly see the movement.

With useLayoutEffect:

Initial render
     ↓
DOM updated
     ↓
useLayoutEffect calculates position
     ↓
DOM/state updated
     ↓
Browser paints

The user normally sees only the final position.


3. useEffect vs useLayoutEffect

This is the most important comparison.

useEffect useLayoutEffect
Runs after browser paint Runs before browser paint
Good for API calls Good for DOM measurement
Good for subscriptions Good for DOM positioning
Good for timers Good for layout calculations
Does not normally block painting Can block painting
Preferred for most side effects Use only when timing requires it

Think of them like this:

useEffect

React
  ↓
DOM update
  ↓
Browser Paint
  ↓
useEffect
useLayoutEffect

React
  ↓
DOM update
  ↓
useLayoutEffect
  ↓
Browser Paint

Important rule

Use useEffect by default. Use useLayoutEffect only when the effect must happen before the browser paints.


4. Basic usage

The syntax is almost identical to useEffect.

import { useLayoutEffect } from "react";

function App() {
  useLayoutEffect(() => {
    console.log("Layout effect executed");
  }, []);

  return <h1>Hello React</h1>;
}

The empty dependency array means:

Component renders
      ↓
DOM updated
      ↓
useLayoutEffect runs
      ↓
Component remains mounted

It runs after the component is mounted.


5. Basic DOM example

One of the most common uses is reading an element's size.

import { useLayoutEffect, useRef } from "react";

function App() {
  const boxRef = useRef(null);

  useLayoutEffect(() => {
    const width = boxRef.current?.getBoundingClientRect().width;

    console.log("Width:", width);
  }, []);

  return (
    <div ref={boxRef}>
      Hello React
    </div>
  );
}

What happens?

Component renders
       ↓
<div> is created in DOM
       ↓
ref points to <div>
       ↓
useLayoutEffect runs
       ↓
getBoundingClientRect()
       ↓
Width is available

This is a perfect example of why useLayoutEffect exists.

You need the actual rendered DOM before continuing.


6. Why not use useEffect here?

You could technically do this:

useEffect(() => {
  const width = boxRef.current?.getBoundingClientRect().width;
}, []);

It may work.

But useLayoutEffect is preferable when the measurement is part of deciding what should be displayed or where it should be positioned before the user sees it.

For example:

Measure element
     ↓
Calculate position
     ↓
Update layout
     ↓
Paint

That is exactly the type of situation where useLayoutEffect is useful.


7. Understanding the complete rendering flow

Suppose we have:

function App() {
  useLayoutEffect(() => {
    console.log("Layout effect");
  }, []);

  useEffect(() => {
    console.log("Normal effect");
  }, []);

  return <div>Hello</div>;
}

Conceptually:

App renders
     ↓
React creates/updates DOM
     ↓
useLayoutEffect runs
     ↓
Browser paints
     ↓
useEffect runs

So:

useLayoutEffect
      ↓
BEFORE paint

useEffect
      ↓
AFTER paint

This timing difference is the entire reason for useLayoutEffect.


8. Scenario 1 — Measure an element

This is one of the most common uses.

import { useLayoutEffect, useRef, useState } from "react";

function Box() {
  const boxRef = useRef(null);
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    if (boxRef.current) {
      setWidth(boxRef.current.getBoundingClientRect().width);
    }
  }, []);

  return (
    <>
      <div ref={boxRef} style={{ width: "300px" }}>
        Hello
      </div>

      <p>Width: {width}px</p>
    </>
  );
}

Data flow

Render
  ↓
<div width = 300px>
  ↓
DOM created
  ↓
useLayoutEffect
  ↓
Measure DOM
  ↓
width = 300
  ↓
setWidth(300)
  ↓
React renders again
  ↓
"Width: 300px"

The important point is that the effect is reading the real DOM size.


9. getBoundingClientRect()

This method is very useful with useLayoutEffect.

const rect = element.getBoundingClientRect();

It gives information such as:

width
height
top
bottom
left
right
x
y

For example:

useLayoutEffect(() => {
  const rect = boxRef.current?.getBoundingClientRect();

  console.log(rect?.width);
  console.log(rect?.height);
  console.log(rect?.top);
  console.log(rect?.left);
}, []);

This is useful for:

  • Tooltips
  • Dropdowns
  • Popovers
  • Menus
  • Modals
  • Custom positioning
  • Responsive calculations

10. Scenario 2 — Position a tooltip

This is a classic real-world example.

Imagine:

       Tooltip
          ↓
     ┌─────────┐
     │ Button  │
     └─────────┘

You need to know where the button is.

import {
  useLayoutEffect,
  useRef,
  useState
} from "react";

function Tooltip() {
  const buttonRef = useRef(null);
  const tooltipRef = useRef(null);

  const [position, setPosition] = useState({
    top: 0,
    left: 0
  });

  useLayoutEffect(() => {
    const button = buttonRef.current;
    const tooltip = tooltipRef.current;

    if (!button || !tooltip) return;

    const buttonRect = button.getBoundingClientRect();

    setPosition({
      top: buttonRect.bottom + 8,
      left: buttonRect.left
    });
  }, []);

  return (
    <>
      <button ref={buttonRef}>
        Hover me
      </button>

      <div
        ref={tooltipRef}
        style={{
          position: "fixed",
          top: position.top,
          left: position.left
        }}
      >
        Tooltip
      </div>
    </>
  );
}

Why useLayoutEffect?

Because positioning is visual.

You don't want:

Wrong position
     ↓
Paint
     ↓
Calculate position
     ↓
Move tooltip

You want:

Render
     ↓
Measure
     ↓
Calculate position
     ↓
Update
     ↓
Paint final result

11. Scenario 3 — Scroll to an element

Another useful scenario is controlling scroll position.

import { useLayoutEffect, useRef } from "react";

function App() {
  const sectionRef = useRef(null);

  useLayoutEffect(() => {
    sectionRef.current?.scrollIntoView({
      behavior: "instant"
    });
  }, []);

  return (
    <div>
      <h1>Page</h1>

      <div style={{ height: "1000px" }} />

      <section ref={sectionRef}>
        Target Section
      </section>
    </div>
  );
}

The idea is:

DOM created
     ↓
Find target element
     ↓
Scroll to target
     ↓
Browser paints

This can help avoid an unwanted visual jump.

However, don't automatically choose useLayoutEffect for every scroll operation. If the scroll does not need to happen before paint, useEffect can be sufficient.


12. Scenario 4 — Prevent visual flickering

Consider a component that initially displays something incorrectly and then corrects it.

For example:

Render:
[Menu too wide]

After measurement:
[Menu correct width]

Using useEffect can produce:

Render
 ↓
Browser paints incorrect menu
 ↓
useEffect
 ↓
Calculate
 ↓
Update
 ↓
Render again

The user might see the incorrect state briefly.

With useLayoutEffect:

Render
 ↓
DOM update
 ↓
Measure
 ↓
Update
 ↓
Render
 ↓
Paint

This is one of the strongest reasons to use useLayoutEffect.


13. Scenario 5 — DOM element positioning

Suppose you have a popup that should appear underneath a button.

function Popup() {
  const buttonRef = useRef(null);
  const [style, setStyle] = useState({});

  useLayoutEffect(() => {
    const rect = buttonRef.current?.getBoundingClientRect();

    if (!rect) return;

    setStyle({
      position: "fixed",
      top: rect.bottom,
      left: rect.left
    });
  }, []);

  return (
    <>
      <button ref={buttonRef}>
        Open
      </button>

      <div style={style}>
        Popup
      </div>
    </>
  );
}

This pattern is common in:

  • Dropdown menus
  • Context menus
  • Date pickers
  • Autocomplete lists
  • Popovers
  • Tooltips

14. Scenario 6 — Synchronize with a third-party DOM library

Sometimes a library directly manipulates the DOM.

Examples include:

  • Chart libraries
  • Animation libraries
  • Rich text editors
  • Map libraries
  • Visualization libraries

You may need to initialize the library after React has created the DOM element.

For example:

import { useLayoutEffect, useRef } from "react";

function Chart() {
  const chartRef = useRef(null);

  useLayoutEffect(() => {
    const element = chartRef.current;

    if (!element) return;

    // Initialize third-party chart
    // new ChartLibrary(element)

    return () => {
      // Destroy chart instance
    };
  }, []);

  return <div ref={chartRef} />;
}

The important flow is:

React creates DOM element
        ↓
ref receives element
        ↓
useLayoutEffect
        ↓
Third-party library initialized
        ↓
Cleanup when component unmounts

15. Scenario 7 — Update DOM styles before paint

Suppose you need to dynamically change a DOM property.

useLayoutEffect(() => {
  if (boxRef.current) {
    boxRef.current.style.transform = "translateX(100px)";
  }
}, []);

This changes the DOM before the browser paints.

This can be useful for certain animation or positioning techniques.

However, in normal React applications, prefer React state and CSS whenever possible.


16. Scenario 8 — Measuring height and updating state

A very common pattern:

function Content() {
  const ref = useRef(null);
  const [height, setHeight] = useState(0);

  useLayoutEffect(() => {
    if (!ref.current) return;

    const height = ref.current.getBoundingClientRect().height;

    setHeight(height);
  }, []);

  return (
    <>
      <div ref={ref}>
        Some dynamic content
      </div>

      <p>Content height: {height}px</p>
    </>
  );
}

Flow

DOM rendered
    ↓
Read actual height
    ↓
setHeight()
    ↓
React re-renders
    ↓
Height displayed

17. useLayoutEffect + useRef

These two Hooks are commonly used together.

useRef

Gives access to a DOM element.

const ref = useRef(null);

Then:

<div ref={ref} />

useLayoutEffect

Runs after the DOM has been updated but before paint.

useLayoutEffect(() => {
  const element = ref.current;

  // read DOM
}, []);

Together:

useRef
  ↓
Get DOM element
  ↓
useLayoutEffect
  ↓
Read/modify DOM

This combination is extremely common.


18. useLayoutEffect + useState

You can measure something and then store the result in state.

const [width, setWidth] = useState(0);

useLayoutEffect(() => {
  const width = elementRef.current?.offsetWidth;

  if (width) {
    setWidth(width);
  }
}, []);

The data flow becomes:

DOM
 ↓
Measurement
 ↓
setState
 ↓
React render
 ↓
Updated UI

19. useLayoutEffect + dependencies

Like useEffect, useLayoutEffect supports dependencies.

useLayoutEffect(() => {
  // code
}, [value]);

It runs when value changes.

For example:

function Box({ width }) {
  const ref = useRef(null);

  useLayoutEffect(() => {
    const actualWidth = ref.current?.getBoundingClientRect().width;

    console.log(actualWidth);
  }, [width]);

  return (
    <div
      ref={ref}
      style={{ width }}
    >
      Content
    </div>
  );
}

When width changes:

width changes
    ↓
Component renders
    ↓
DOM width changes
    ↓
useLayoutEffect runs
    ↓
Measure new width

20. Dependency array behavior

Run after every render

useLayoutEffect(() => {
  // runs after every render
});

Run only after initial mount

useLayoutEffect(() => {
  // runs on mount
}, []);

Run when a dependency changes

useLayoutEffect(() => {
  // runs when width changes
}, [width]);

21. Cleanup function

useLayoutEffect also supports cleanup.

useLayoutEffect(() => {
  // setup

  return () => {
    // cleanup
  };
}, []);

For example:

useLayoutEffect(() => {
  const handleResize = () => {
    console.log("Window resized");
  };

  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize);
  };
}, []);

Lifecycle

Component mounted
      ↓
useLayoutEffect
      ↓
Event listener added
      ↓
Component unmounts
      ↓
Cleanup
      ↓
Event listener removed

But note: a resize listener does not necessarily need useLayoutEffect; useEffect is usually enough unless the listener's setup specifically must happen before paint.


22. useLayoutEffect vs useEffect for API calls

Don't do this unnecessarily:

useLayoutEffect(() => {
  fetch("/api/products");
}, []);

Prefer:

useEffect(() => {
  fetch("/api/products");
}, []);

Why?

API requests are not usually related to browser layout.

There is no benefit in blocking the browser's paint while preparing an API request.

Rule

API / network / subscription
        ↓
useEffect
DOM measurement / DOM positioning
        ↓
useLayoutEffect

23. useLayoutEffect and useMemo

These Hooks solve completely different problems.

useMemo

Optimizes expensive calculations.

const result = useMemo(() => {
  return expensiveCalculation(data);
}, [data]);

useLayoutEffect

Controls when an effect runs relative to browser painting.

useLayoutEffect(() => {
  // DOM measurement
}, []);

So:

useMemo
→ optimize calculation

useLayoutEffect
→ synchronize with DOM/layout before paint

24. useLayoutEffect and useCallback

useCallback caches a function reference.

const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

useLayoutEffect performs an effect.

useLayoutEffect(() => {
  // DOM operation
}, []);

They solve different problems.


25. useLayoutEffect and useRef

This is a more important relationship.

useRef
   ↓
Get DOM element
   ↓
useLayoutEffect
   ↓
Measure/manipulate DOM

Example:

const ref = useRef(null);

useLayoutEffect(() => {
  console.log(ref.current?.getBoundingClientRect());
}, []);

This is a very common pattern.


26. useLayoutEffect with forwardRef

In reusable components, a parent may need access to a child's DOM element.

For example:

const Input = forwardRef(function Input(props, ref) {
  return <input ref={ref} {...props} />;
});

Then:

const inputRef = useRef(null);

useLayoutEffect(() => {
  inputRef.current?.focus();
}, []);

return <Input ref={inputRef} />;

The important concept is:

Parent
  ↓
ref
  ↓
Child DOM element
  ↓
useLayoutEffect
  ↓
DOM operation

27. useLayoutEffect with ResizeObserver

For real-world responsive UI, ResizeObserver is very useful.

Instead of measuring only once:

useLayoutEffect(() => {
  // measure once
}, []);

you can observe size changes.

import {
  useLayoutEffect,
  useRef,
  useState
} from "react";

function Box() {
  const ref = useRef(null);
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    if (!ref.current) return;

    const observer = new ResizeObserver((entries) => {
      const width = entries[0].contentRect.width;

      setWidth(width);
    });

    observer.observe(ref.current);

    return () => observer.disconnect();
  }, []);

  return (
    <div ref={ref}>
      Width: {width}px
    </div>
  );
}

Why this is useful?

The element can change size because of:

  • Window resizing
  • Parent size changes
  • CSS changes
  • Responsive layout
  • Dynamic content

The observer detects the changes.


28. Real-world example — Responsive component

Imagine a component that behaves differently based on its actual width.

Width < 500px
    ↓
Mobile layout

Width >= 500px
    ↓
Desktop layout

You can measure the component and store its width.

const [width, setWidth] = useState(0);

Then:

if (width < 500) {
  // mobile behavior
}

This can be useful for components that need to respond to their own size, rather than just the browser window size.


29. Real-world example — Modal positioning

Imagine a modal that must appear relative to another element.

Button
   ↓
Modal

The component can:

  1. Render the button.
  2. Get the button's DOM position.
  3. Calculate the modal position.
  4. Update the modal position.
  5. Paint the final layout.
Button rendered
      ↓
getBoundingClientRect()
      ↓
Calculate modal position
      ↓
Update state
      ↓
Final paint

This is an appropriate use case for useLayoutEffect.


30. Real-world example — Dropdown

Suppose a dropdown should appear below a button.

┌──────────────┐
│ Select       │
└──────────────┘
       ↓
┌──────────────┐
│ Option 1     │
│ Option 2     │
│ Option 3     │
└──────────────┘

You may need:

const rect = buttonRef.current.getBoundingClientRect();

Then:

top = rect.bottom
left = rect.left

This is one of the practical reasons UI libraries internally need layout measurement.


31. Real-world example — Preventing content jump

Suppose an image is loaded and changes the size of a component.

You may need to measure the layout before showing the final UI.

useLayoutEffect can help when you must synchronously measure or adjust the layout before paint.

However, for image dimensions specifically, it is often better to solve the layout at the CSS/HTML level:

img {
  width: 100%;
  height: auto;
}

or reserve space using known dimensions/aspect ratio.

Important

Don't use useLayoutEffect to compensate for poor CSS layout when CSS can solve the problem.


32. Real-world example — Animation setup

Sometimes an animation requires reading the initial DOM position before changing it.

Conceptually:

Read initial position
       ↓
Apply starting state
       ↓
Browser paints
       ↓
Animation begins

useLayoutEffect can be useful for this kind of DOM animation setup.

For example:

useLayoutEffect(() => {
  const element = boxRef.current;

  if (!element) return;

  const rect = element.getBoundingClientRect();

  // Use rect to calculate animation starting position
}, []);

For complex animations, however, dedicated animation libraries may be better.


33. TypeScript example

The main TypeScript difference is typing the DOM ref.

For a div:

const ref = useRef<HTMLDivElement | null>(null);

Then:

useLayoutEffect(() => {
  const element = ref.current;

  if (!element) return;

  const rect = element.getBoundingClientRect();

  console.log(rect.width);
}, []);

Complete example:

import {
  useLayoutEffect,
  useRef,
  useState
} from "react";

function Box() {
  const boxRef = useRef<HTMLDivElement | null>(null);

  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    const element = boxRef.current;

    if (!element) return;

    setWidth(element.getBoundingClientRect().width);
  }, []);

  return (
    <div>
      <div ref={boxRef}>
        Hello React
      </div>

      <p>Width: {width}px</p>
    </div>
  );
}

export default Box;

34. Common DOM ref types in TypeScript

useRef<HTMLDivElement | null>(null);
useRef<HTMLInputElement | null>(null);
useRef<HTMLButtonElement | null>(null);
useRef<HTMLFormElement | null>(null);

The type should match the actual DOM element.


35. Important behavior: useLayoutEffect can trigger another render

Consider:

useLayoutEffect(() => {
  setWidth(500);
}, []);

The flow is:

Render #1
   ↓
DOM updated
   ↓
useLayoutEffect
   ↓
setWidth(500)
   ↓
Render #2
   ↓
DOM updated
   ↓
Browser paints

This is important.

useLayoutEffect itself doesn't magically change state without consequences.

If you call a state setter inside it, React can perform another render before the browser paints.


36. Why can this be useful?

Suppose the initial render doesn't know the actual DOM size.

Initial render
     ↓
Measure DOM
     ↓
Calculate correct layout
     ↓
Update state
     ↓
Render final layout
     ↓
Paint

This can prevent the user from seeing the incorrect intermediate layout.


37. But there is a cost

Because useLayoutEffect runs before painting, expensive work can delay the screen from appearing.

For example:

useLayoutEffect(() => {
  // Very expensive calculation
}, []);

If this takes 500 ms:

React
 ↓
useLayoutEffect
 ↓
500 ms blocking work
 ↓
Browser paint

The user may experience a delayed screen.

Therefore:

Keep useLayoutEffect work small and focused.


38. Common mistake — using it everywhere

Bad approach:

useLayoutEffect(() => {
  fetchData();
}, []);

or:

useLayoutEffect(() => {
  console.log("Component rendered");
}, []);

when there is no layout reason.

Prefer:

useEffect(() => {
  fetchData();
}, []);

Use useLayoutEffect when layout/DOM timing actually matters.


39. Common mistake — confusing it with useEffect

Remember:

useEffect
    ↓
After paint

useLayoutEffect
    ↓
Before paint

Don't choose useLayoutEffect simply because it sounds more powerful.

It is a specialized tool.


40. Common mistake — doing expensive work

Avoid:

useLayoutEffect(() => {
  for (let i = 0; i < 1000000000; i++) {
    // expensive work
  }
}, []);

Because painting is delayed.

If the work does not need to happen before paint, move it to:

useEffect()

or another appropriate mechanism.


41. Common mistake — infinite update loops

Be careful with state updates.

For example:

useLayoutEffect(() => {
  setWidth(
    boxRef.current?.getBoundingClientRect().width
  );
});

There is no dependency array.

This can cause:

Render
 ↓
useLayoutEffect
 ↓
setState
 ↓
Render
 ↓
useLayoutEffect
 ↓
setState
 ↓
Render
 ↓
...

This can become an infinite render loop.

Be especially careful when updating state based on DOM measurements.


42. Common mistake — unnecessary DOM manipulation

Don't use:

useLayoutEffect(() => {
  document.querySelector(".box").style.color = "red";
}, []);

when React can simply do:

<div style={{ color: "red" }}>

React should normally control the UI.

Use direct DOM manipulation when you genuinely need it.


43. Common mistake — using it when CSS is enough

Don't use:

useLayoutEffect(() => {
  element.style.width = "100%";
}, []);

when CSS can handle it:

width: 100%;

React + CSS should be your first choice.

useLayoutEffect is primarily for cases where you need to synchronize React with actual browser layout.


44. Important: SSR and Server Components

useLayoutEffect is a browser-side Hook.

It needs the DOM.

Therefore, using it in server rendering environments requires care.

You may see warnings such as:

useLayoutEffect does nothing on the server

The reason is simple:

Server
 ↓
No browser DOM
 ↓
Cannot measure layout

Whereas:

Browser
 ↓
DOM exists
 ↓
Layout can be measured

In modern React applications using frameworks such as Next.js, pay attention to whether the component is rendered on the server or client.


45. useLayoutEffect in React Server Components

React Server Components cannot use client-only Hooks such as:

useState
useEffect
useLayoutEffect
useRef

unless the component is a client component in a framework that supports that model.

For example, in Next.js, a component that needs browser-side Hooks generally needs to be marked as a client component:

"use client";

The exact rules depend on the framework and rendering model.


46. useLayoutEffect and Strict Mode

In development, React Strict Mode can cause effects to run through an additional setup/cleanup cycle.

So don't assume:

useLayoutEffect runs exactly once

in development simply because you wrote:

useLayoutEffect(() => {
  // ...
}, []);

Your effect should therefore be written so that setup and cleanup are safe and repeatable.

For example:

useLayoutEffect(() => {
  const observer = new ResizeObserver(...);

  observer.observe(element);

  return () => {
    observer.disconnect();
  };
}, []);

The cleanup is important.


47. useLayoutEffect and concurrent rendering

A very important conceptual point:

useLayoutEffect does not mean:

"Run this immediately when React starts rendering."

React rendering can be interrupted or discarded.

The effect runs as part of the committed DOM update.

Think:

React render
      ↓
React determines what should change
      ↓
Commit DOM changes
      ↓
useLayoutEffect
      ↓
Paint

So it is tied to the commit phase, not the initial render calculation.


48. Render phase vs commit phase

This distinction is useful for interviews.

Render phase

React determines what the UI should look like.

Component function
       ↓
React calculates changes

Commit phase

React applies changes to the actual DOM.

React
 ↓
DOM updated

Layout effect

Then:

DOM updated
 ↓
useLayoutEffect
 ↓
Browser paint

So useLayoutEffect runs after DOM mutation during the commit process, before the browser paints.


49. useLayoutEffect vs useInsertionEffect

React also has:

useInsertionEffect()

This is a much more specialized Hook.

It is primarily intended for CSS-in-JS libraries that need to insert styles before layout effects run.

For normal application development:

useEffect
       ↓
Most side effects

useLayoutEffect
       ↓
DOM measurement/layout

useInsertionEffect
       ↓
Very specialized style insertion

You generally don't need useInsertionEffect for normal application code.


50. A practical decision-making rule

When you want to use an effect, ask:

Question 1

Does this involve the browser DOM/layout?

No

Use:

useEffect()

Question 2

Does it need to happen before the user sees the updated screen?

No

Use:

useEffect()

Question 3

Does it need to measure or modify layout before paint?

Yes

Consider:

useLayoutEffect()

51. Simple decision table

Requirement Hook
API call useEffect
Fetch data useEffect
WebSocket subscription useEffect
Timer useEffect
Event listener Usually useEffect
Read DOM size before paint useLayoutEffect
Calculate tooltip position useLayoutEffect
Calculate popup position useLayoutEffect
Read element position useLayoutEffect
Prevent layout flicker useLayoutEffect
DOM animation setup Sometimes useLayoutEffect
Third-party DOM library Sometimes useLayoutEffect
Expensive calculation Usually not useLayoutEffect
Normal state calculation Neither; use normal render/memoization as appropriate

52. A very important distinction

Don't think:

"useLayoutEffect is a better version of useEffect."

That's incorrect.

Think:

"useLayoutEffect is a specialized version of an effect whose timing is important for browser layout."

So:

useEffect
   ↓
General-purpose side effects

while:

useLayoutEffect
   ↓
DOM/layout synchronization

53. Complete practical example

Here's a realistic tooltip-like example:

import {
  useLayoutEffect,
  useRef,
  useState
} from "react";

function Tooltip() {
  const buttonRef = useRef<HTMLButtonElement | null>(null);

  const [position, setPosition] = useState({
    top: 0,
    left: 0
  });

  useLayoutEffect(() => {
    const button = buttonRef.current;

    if (!button) return;

    const rect = button.getBoundingClientRect();

    setPosition({
      top: rect.bottom + 8,
      left: rect.left
    });
  }, []);

  return (
    <>
      <button ref={buttonRef}>
        Help
      </button>

      <div
        style={{
          position: "fixed",
          top: position.top,
          left: position.left
        }}
      >
        This is a tooltip
      </div>
    </>
  );
}

Overall behavior

1. React renders button
        ↓
2. Button is added to DOM
        ↓
3. ref gets button
        ↓
4. useLayoutEffect runs
        ↓
5. getBoundingClientRect()
        ↓
6. Calculate tooltip position
        ↓
7. setPosition()
        ↓
8. React renders tooltip at correct position
        ↓
9. Browser paints

This is the kind of problem useLayoutEffect is designed for.


54. Another practical example — measure a dynamic component

import {
  useLayoutEffect,
  useRef,
  useState
} from "react";

function Card() {
  const cardRef = useRef<HTMLDivElement | null>(null);

  const [height, setHeight] = useState(0);

  useLayoutEffect(() => {
    const card = cardRef.current;

    if (!card) return;

    setHeight(card.getBoundingClientRect().height);
  }, []);

  return (
    <div>
      <div ref={cardRef}>
        <h2>Product</h2>
        <p>
          This content determines the actual card height.
        </p>
      </div>

      <p>Card height: {height}px</p>
    </div>
  );
}

The important concept is:

React doesn't know the final browser layout
until the DOM exists.

useLayoutEffect gives you a point where
the DOM exists but the browser has not
painted the updated screen yet.

55. When NOT to use useLayoutEffect

Avoid it for:

API requests

useEffect(() => {
  fetch("/api/products");
}, []);

Data fetching

useEffect(() => {
  loadProducts();
}, []);

Timers

useEffect(() => {
  const timer = setTimeout(...);

  return () => clearTimeout(timer);
}, []);

Logging

useEffect(() => {
  console.log("Component mounted");
}, []);

Regular subscriptions

Usually:

useEffect(...)

Normal state synchronization

First check whether the state can simply be derived during render.


56. When SHOULD you use useLayoutEffect?

Use it when you genuinely need:

1. DOM measurement

width
height
top
left

2. DOM positioning

tooltip
popup
dropdown
popover

3. Pre-paint DOM adjustment

Read layout
 ↓
Calculate
 ↓
Adjust
 ↓
Paint

4. Preventing visual flicker

When the incorrect intermediate UI would otherwise be visible.

5. Certain animation setup

When initial DOM measurements are required before painting.

6. Integrating with DOM-based libraries

When the library must interact with an already-created DOM element before paint.


57. Best practices

Use useEffect by default

This should be your normal choice.

Need an effect?
     ↓
Try useEffect first
     ↓
Does it need pre-paint layout synchronization?
     ↓
Yes → useLayoutEffect

Keep layout effects small

Avoid expensive operations.

Use useRef for DOM access

const ref = useRef(null);

rather than repeatedly querying the DOM.

Always clean up subscriptions/observers

return () => {
  observer.disconnect();
};

Avoid unnecessary state updates

Don't measure something and call setState if you don't actually need the result in the UI.

Prefer CSS where possible

Don't use useLayoutEffect to solve problems that CSS can solve.

Be careful with SSR

useLayoutEffect requires a browser environment.

Make effects resilient to Strict Mode

Always write proper setup and cleanup logic.


58. Interview-focused questions

What is useLayoutEffect?

useLayoutEffect is a React Hook that runs after React updates the DOM but before the browser paints the updated screen. It is mainly used for DOM measurement, positioning, and pre-paint layout synchronization.

What is the difference between useEffect and useLayoutEffect?

useEffect runs after the browser paints, while useLayoutEffect runs after DOM updates but before paint.

When should you use useLayoutEffect?

Use it when you need to synchronously read or modify DOM layout before the user sees the updated screen, such as measuring elements or positioning tooltips.

Should you use useLayoutEffect for API calls?

No. Normally use useEffect because API calls do not need to block browser painting.

Why can useLayoutEffect cause performance problems?

Because it runs before painting. Expensive work inside it can delay the browser from displaying the updated UI.

Can useLayoutEffect update state?

Yes.

useLayoutEffect(() => {
  setWidth(500);
}, []);

This can cause another render before the browser paints.

What is the relationship between useRef and useLayoutEffect?

useRef can provide access to a DOM element, while useLayoutEffect can then measure or manipulate that element before paint.

Does useLayoutEffect run during rendering?

No. It runs after React has committed the DOM changes.


59. The easiest way to remember it

Remember this one sentence:

useLayoutEffect = "The DOM is updated, but the user hasn't seen it yet."

So you can:

Read DOM
   ↓
Measure DOM
   ↓
Calculate position
   ↓
Adjust layout
   ↓
Browser paints

Whereas useEffect is:

DOM updated
   ↓
Browser paints
   ↓
Effect runs

60. Final summary

useLayoutEffect is not something you should use instead of useEffect.

It is a specialized Hook for situations where DOM layout and timing before browser paint matter.

The core concept is:

                    React
                      │
                   Render
                      │
                 DOM Update
                      │
            ┌─────────┴─────────┐
            │                   │
    useLayoutEffect          Browser Paint
            │                   │
      Measure/adjust             │
            │                   │
            └─────────┬─────────┘
                      │
                 Final UI

The most important rules

  1. Use useEffect by default.
  2. Use useLayoutEffect when you need DOM/layout work before paint.
  3. Use it for measurements, positioning, and preventing visual layout flicker.
  4. useRef + useLayoutEffect is a common combination for DOM measurement.
  5. Don't use it for API calls or ordinary side effects.
  6. Keep the code inside it fast because it can delay painting.
  7. Be careful when calling state setters inside it.
  8. Always clean up observers, listeners, and third-party resources.
  9. Remember that it is browser/DOM-oriented and needs care with SSR.

The key interview answer is:

useLayoutEffect runs synchronously after React updates the DOM but before the browser paints. It is mainly used when we need to measure or modify the DOM/layout before the user sees the result. For normal side effects such as API calls, subscriptions, and timers, useEffect should generally be preferred.

← Back to Articles