useLayoutEffect Hook

🪝 Introduction to useLayoutEffect

The useLayoutEffect Hook is a React Hook that allows you to perform synchronous side effects after React has updated the DOM but before the browser repaints the screen. It is useful when you need to measure, read, or modify the layout before the user sees the updated interface.

Important

Unlike useEffect, useLayoutEffect blocks the browser from repainting until the effect has finished executing.

🎯 Why Use useLayoutEffect?

Most side effects should use useEffect. However, some operations require immediate access to the DOM before the browser paints. useLayoutEffect ensures these updates happen synchronously, preventing visual glitches such as flickering.

  • Measure the size or position of DOM elements.
  • Adjust layout before the browser repaints.
  • Synchronize scrolling or element positioning.
  • Prevent layout flickering during rendering.

⚙️ Syntax

Basic Syntax

useLayoutEffect(() => {
  // Synchronous side effect

  return () => {
    // Cleanup (optional)
  };
}, [dependencies]);
PartDescription
Effect FunctionRuns immediately after the DOM is updated.
Cleanup FunctionRuns before the effect executes again or before unmounting.
Dependency ArrayDetermines when the effect should execute.

🔄 How useLayoutEffect Works

Component Renders
React Updates the DOM
useLayoutEffect Executes
DOM Measurements or Updates Occur
Browser Paints the Screen

💻 Example 1: Measuring an Element

Reading Element Size

import { useLayoutEffect, useRef } from "react";

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

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

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

The measurement occurs before the browser paints, ensuring that layout information is accurate without causing visible flickering.

📐 Example 2: Adjusting Layout

Updating Styles Before Paint

import { useLayoutEffect, useRef } from "react";

function Highlight() {
  const elementRef = useRef(null);

  useLayoutEffect(() => {
    elementRef.current.style.backgroundColor = "yellow";
  }, []);

  return <div ref={elementRef}>Highlighted Text</div>;
}

The background color is applied before the browser displays the element, resulting in a smooth visual update.

📊 useEffect vs useLayoutEffect

FeatureuseEffectuseLayoutEffect
Execution TimeAfter the browser paints.Before the browser paints.
Blocks Rendering❌ No✅ Yes
Best ForData fetching, subscriptions, timers.DOM measurements and layout updates.
PerformanceBetter for most effects.Should be used only when necessary.

⏱️ Rendering Timeline

🎯 Common Use Cases

Measure an element's size or position before it becomes visible to the user.

Adjust scroll positions immediately after the DOM updates to prevent visible jumps.

Prepare animation starting positions before the browser paints the next frame.

Position tooltips, dropdowns, or popovers based on measured element dimensions.

⚠️ When Not to Use useLayoutEffect

  • Fetching data from an API.
  • Setting timers or intervals.
  • Listening to external events that do not require layout measurements.
  • Any side effect that does not depend on the DOM layout.

Warning

Because useLayoutEffect blocks the browser from painting, excessive use can reduce application performance. Prefer useEffect unless synchronous DOM access is required.

✅ Best Practices

  • Use useLayoutEffect only for layout-related work.
  • Keep the effect as short and efficient as possible.
  • Always clean up subscriptions or listeners when necessary.
  • Prefer useEffect for non-layout side effects.
  • Measure the DOM before making layout-dependent updates.

📚 Official Resource

Learn more about useLayoutEffect in the official React documentation at React useLayoutEffect Documentation.

Summary

The useLayoutEffect Hook executes after React updates the DOM but before the browser repaints the screen. It is ideal for measuring elements, synchronizing layouts, and preventing visual flickering. Since it blocks rendering, it should be used only when synchronous DOM access is necessary, while useEffect remains the preferred choice for most side effects.