The useLayoutEffect hook has an identical signature to useEffect, but it executes synchronously after all DOM mutations are committed, but before the browser paints the screen.
This prevents visual screen flickering when measuring DOM dimensions or applying layout transformations directly to DOM elements.
flowchart TD
Render["React Component Render"] --> DOMMutate["DOM Mutations Committed"]
DOMMutate --> LayoutEffect["useLayoutEffect Fires (Synchronous Block)"]
LayoutEffect --> Paint["Browser Paints Screen"]
Paint --> Effect["useEffect Fires (Asynchronous)"]
| Hook Name | Execution Timing | Screen Paint | Primary Use Case |
|---|---|---|---|
useEffect |
Asynchronous (Non-blocking) | Fires after screen paint | Data fetching, event subscriptions, timers |
useLayoutEffect |
Synchronous (Blocking) | Fires before screen paint | Tooltip positioning, measuring element width/height |
import React, { useState, useRef, useLayoutEffect } from 'react';
export default function AutoPositionedTooltip({ text }) {
const [tooltipHeight, setTooltipHeight] = useState(0);
const tooltipRef = useRef(null);
// useLayoutEffect measures DOM element BEFORE browser paints screen to prevent layout flicker
useLayoutEffect(() => {
if (tooltipRef.current) {
const { height } = tooltipRef.current.getBoundingClientRect();
setTooltipHeight(height);
}
}, [text]);
return (
<div style={{ position: 'relative', display: 'inline-block' }}>
<div
ref={tooltipRef}
style={{
position: 'absolute',
top: `-${tooltipHeight + 8}px`,
backgroundColor: '#1e293b',
color: '#ffffff',
padding: '4px 8px',
borderRadius: '4px',
fontSize: '12px',
}}
>
{text}
</div>
<button>Hover Target</button>
</div>
);
}
useEffect by Default: useLayoutEffect blocks browser painting. Always start with standard useEffect and switch to useLayoutEffect only if visual screen flicker occurs during DOM measurements.useLayoutEffect triggers a console warning during SSR because server rendering has no browser paint stage.Explain why measuring an element's getBoundingClientRect() inside useEffect can cause a noticeable visual jump on the user's screen.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.