useLayoutEffect

what is useLayoutEffect ?

  • Profile picture of Mcs
  • by Mcs July 3, 2025

useLayoutEffect() is a React Hook that works just like useEffect() — but it runs synchronously after all DOM mutations and before the browser paints the screen.

That allows for performing side effects that require synchronous DOM mutations or measurements. It is similar to useEffect but differs in its execution timing.

When to Use useLayoutEffect()

Use useLayoutEffect() when:

  1. You need to measure layout (e.g., get element size or position)
  2. You need to synchronously update the DOM before the user sees it (to avoid flickering)
  3. You’re working with animations or scroll positioning

Syntax

useLayoutEffect(() => {
 // Your logic here (DOM reads or updates)
 return () => {
   // Cleanup if needed
 };
}, [dependencies]);

Example: DOM Measurement

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

function Box() {
 const boxRef = useRef();
 const [boxWidth, setBoxWidth] = useState(0);

 useLayoutEffect(() => {
   const width = boxRef.current.offsetWidth;
   setBoxWidth(width);
 }, []);

 return (
   <>
     <div ref={boxRef} style={{ width: '300px', border: '1px solid black' }}>
       I am a box
     </div>
     <p>Width: {boxWidth}px</p>
   </>
 );
}

This ensures boxWidth is set before the user sees the screen.

Summary

FeatureDescription
useLayoutEffect()Like useEffect but runs before paint
Use whenYou must read or change the DOM before screen updates
Common use casesMeasure layout, fix scroll jump, handle animations

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.