
what is useLayoutEffect ?
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:
- You need to measure layout (e.g., get element size or position)
- You need to synchronously update the DOM before the user sees it (to avoid flickering)
- 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
Feature | Description |
---|---|
useLayoutEffect() | Like useEffect but runs before paint |
Use when | You must read or change the DOM before screen updates |
Common use cases | Measure layout, fix scroll jump, handle animations |
Comments
Add new comment