Understanding useLayoutEffect Hook
Learn when and how to use useLayoutEffect for synchronous DOM updates. Master DOM measurements and prevent visual flicker with useLayoutEffect.

What is useLayoutEffect?#
useLayoutEffect is a React hook that runs synchronously after all DOM mutations but before the browser paints. This makes it perfect for DOM measurements and synchronous DOM updates that need to happen before the user sees the visual changes. Unlike useEffect, which runs asynchronously after the browser paints, useLayoutEffect runs synchronously, blocking the browser from painting until it completes.
The key difference is timing: useEffect runs after the browser has painted, while useLayoutEffect runs before. This means useLayoutEffect can cause performance issues if you perform expensive operations, as it blocks the browser from painting. However, for DOM measurements and preventing visual flicker, it's the right tool for the job.
Installation#
useLayoutEffect is part of React core (React 16.8+), so no additional installation is needed:
npm list reactDifference from useEffect#
The execution order is crucial to understand:
// useEffect - runs after paint (asynchronous)
useEffect(() => {
// Runs after browser paints
// User might see flicker if DOM changes here
console.log('Effect runs after paint');
}, []);
// useLayoutEffect - runs before paint (synchronous)
useLayoutEffect(() => {
// Runs before browser paints
// DOM changes happen before user sees anything
console.log('Layout effect runs before paint');
}, []);Execution Timeline#
Here's the order of execution:
- Component renders
- DOM mutations happen
- useLayoutEffect runs (synchronously)
- Browser paints
- useEffect runs (asynchronously)
Example: Measuring Element Dimensions#
One of the most common use cases is measuring DOM elements:
import { useState, useLayoutEffect, useRef } from 'react';
function MeasuredComponent() {
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const ref = useRef(null);
useLayoutEffect(() => {
if (ref.current) {
const { width, height } = ref.current.getBoundingClientRect();
setDimensions({ width, height });
}
}, []);
return (
<div ref={ref} className="measured-element">
<p>Width: {dimensions.width}px</p>
<p>Height: {dimensions.height}px</p>
</div>
);
}Example: Preventing Visual Flicker#
When you need to position elements based on measurements, useLayoutEffect prevents flicker:
function Tooltip({ children, targetRef }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
const tooltipRef = useRef(null);
useLayoutEffect(() => {
if (targetRef.current && tooltipRef.current) {
const targetRect = targetRef.current.getBoundingClientRect();
const tooltipRect = tooltipRef.current.getBoundingClientRect();
// Calculate position to center tooltip above target
const x = targetRect.left + (targetRect.width / 2) - (tooltipRect.width / 2);
const y = targetRect.top - tooltipRect.height - 10;
setPosition({ x, y });
}
}, [targetRef]);
return (
<div
ref={tooltipRef}
className="tooltip"
style={{
position: 'fixed',
left: `${position.x}px`,
top: `${position.y}px`,
opacity: position.x === 0 ? 0 : 1 // Hide until positioned
}}
>
{children}
</div>
);
}Example: Scroll Position Restoration#
Restoring scroll position before the browser paints:
function ScrollRestore({ scrollKey }) {
const containerRef = useRef(null);
useLayoutEffect(() => {
const savedPosition = sessionStorage.getItem(`scroll-${scrollKey}`);
if (savedPosition && containerRef.current) {
containerRef.current.scrollTop = parseInt(savedPosition, 10);
}
}, [scrollKey]);
const handleScroll = () => {
if (containerRef.current) {
sessionStorage.setItem(
`scroll-${scrollKey}`,
containerRef.current.scrollTop.toString()
);
}
};
return (
<div
ref={containerRef}
onScroll={handleScroll}
className="scrollable-container"
>
{/* Content */}
</div>
);
}Example: Animation Setup#
Setting up animations before the first paint:
function AnimatedBox({ isVisible }) {
const boxRef = useRef(null);
useLayoutEffect(() => {
if (boxRef.current) {
// Set initial state before paint
boxRef.current.style.transform = 'translateX(-100%)';
boxRef.current.style.opacity = '0';
// Trigger animation after a frame
requestAnimationFrame(() => {
if (boxRef.current) {
boxRef.current.style.transition = 'all 0.3s ease';
boxRef.current.style.transform = 'translateX(0)';
boxRef.current.style.opacity = '1';
}
});
}
}, [isVisible]);
return (
<div ref={boxRef} className="animated-box">
Content
</div>
);
}When to Use useLayoutEffect#
- DOM measurements - Getting element dimensions, positions
- Preventing visual flicker - Positioning elements based on measurements
- Synchronous DOM updates - Changes that must happen before paint
- Animation setup - Setting initial animation states
- Scroll restoration - Restoring scroll positions
- Focus management - Setting focus before paint
When NOT to Use useLayoutEffect#
- Data fetching - Use useEffect instead
- Subscriptions - Use useEffect instead
- Expensive computations - Blocks painting
- Most side effects - useEffect is usually better
Performance Considerations#
Since useLayoutEffect runs synchronously and blocks painting, be careful with expensive operations:
// ❌ Bad - Expensive operation blocks paint
useLayoutEffect(() => {
const result = expensiveComputation(); // Blocks browser!
setData(result);
}, []);
// ✅ Good - Use useEffect for expensive operations
useEffect(() => {
const result = expensiveComputation(); // Doesn't block paint
setData(result);
}, []);
// ✅ Good - Quick DOM measurement is fine
useLayoutEffect(() => {
const rect = elementRef.current.getBoundingClientRect();
setPosition(rect); // Fast, synchronous is OK
}, []);Best Practices#
- Use useLayoutEffect only when you need synchronous DOM updates
- Keep operations fast - avoid expensive computations
- Use useEffect for most side effects
- Measure DOM elements when needed, not on every render
- Consider using CSS for animations instead of JavaScript when possible
- Test for visual flicker - if you see it, useLayoutEffect might help
Common Patterns#
// Pattern 1: Measure and update
useLayoutEffect(() => {
const measurements = measureElement();
updateLayout(measurements);
}, [dependencies]);
// Pattern 2: Restore state before paint
useLayoutEffect(() => {
restoreState();
}, []);
// Pattern 3: Setup before animation
useLayoutEffect(() => {
setupAnimation();
return () => cleanupAnimation();
}, []);useLayoutEffect is a powerful tool for specific use cases where you need synchronous DOM updates. While it should be used sparingly due to performance implications, it's essential for preventing visual flicker and ensuring smooth user experiences when working with DOM measurements and positioning.