🪝 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
🎯 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]);| Part | Description |
|---|---|
| Effect Function | Runs immediately after the DOM is updated. |
| Cleanup Function | Runs before the effect executes again or before unmounting. |
| Dependency Array | Determines when the effect should execute. |
🔄 How useLayoutEffect Works
💻 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
| Feature | useEffect | useLayoutEffect |
|---|---|---|
| Execution Time | After the browser paints. | Before the browser paints. |
| Blocks Rendering | ❌ No | ✅ Yes |
| Best For | Data fetching, subscriptions, timers. | DOM measurements and layout updates. |
| Performance | Better for most effects. | Should be used only when necessary. |
⏱️ Rendering Timeline
React renders the component.
React updates the DOM.
useLayoutEffect executes synchronously.
The browser paints the updated interface.
useEffect executes after the browser has painted.
🎯 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
✅ 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.