0
0
ReactConceptBeginner · 3 min read

When to Use useLayoutEffect in React: Key Guide

Use useLayoutEffect in React when you need to read or change the DOM immediately after React has updated it but before the browser paints. It is useful for synchronizing layout, measuring elements, or making visual adjustments that must happen before the user sees the screen.
⚙️

How It Works

useLayoutEffect runs synchronously right after React updates the DOM but before the browser paints the screen. Think of it like checking and fixing your room before guests arrive, so they only see the final tidy state.

This means any changes you make inside useLayoutEffect happen before the user sees the page, preventing flickers or layout jumps. It blocks the browser from painting until your effect finishes, unlike useEffect which runs after painting.

💻

Example

This example uses useLayoutEffect to measure a box's width right after it renders and sets that width in state to display it.

javascript
import React, { useState, useRef, useLayoutEffect } from 'react';

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

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

  return (
    <div>
      <div ref={boxRef} style={{ width: '200px', height: '100px', backgroundColor: 'lightblue' }}>
        Box
      </div>
      <p>Box width: {width}px</p>
    </div>
  );
}

export default BoxWidth;
Output
Box width: 200px
🎯

When to Use

Use useLayoutEffect when you need to:

  • Measure DOM elements immediately after render to avoid flicker.
  • Synchronize animations or styles that depend on layout.
  • Make visual updates that must happen before the browser paints.

For example, if you want to adjust scroll position, measure element sizes, or fix layout shifts, useLayoutEffect ensures these happen before the user sees the page.

For most side effects like data fetching or logging, use useEffect instead, as it does not block painting.

Key Points

  • Runs synchronously after DOM updates but before paint.
  • Blocks browser paint until effect finishes.
  • Ideal for layout reads and visual fixes.
  • Use useEffect for non-layout side effects.
  • Helps prevent flicker and layout jumps.

Key Takeaways

Use useLayoutEffect to read or change the DOM before the browser paints.
It prevents flicker by running synchronously after DOM updates.
Ideal for measuring elements or fixing layout shifts immediately.
For non-layout side effects, prefer useEffect to avoid blocking paint.
UseLayoutEffect helps keep UI stable and smooth during updates.