useLayoutEffect() is a React Hook that runs synchronously after the DOM is updated but before the browser paints the screen.
It is mainly used for DOM measurements and layout updates that must happen before the user sees anything.
useLayoutEffect(() => {
// DOM read/write here
});
✅ What is useEffect()?
useEffect() runs after the browser paints the screen.
It is asynchronous and does not block rendering.
useEffect(() => {
// Side effects here
});
🔥 Key Difference (Timing)
Render → DOM updated → useLayoutEffect → Paint → useEffect
🆚 Comparison Table
| Feature | useEffect | useLayoutEffect |
|---|---|---|
| Execution | After paint | Before paint |
| Blocking | ❌ Non-blocking | ✔ Blocks paint |
| Performance | Better | Can hurt performance |
| DOM measurement | ❌ Risky | ✔ Safe |
| Use case | Side effects | Layout & measurements |
🧪 Example — DOM Measurement
❌ Using useEffect (may cause flicker)
useEffect(() => {
const height = ref.current.offsetHeight;
setHeight(height);
}, []);
✅ Using useLayoutEffect (correct)
useLayoutEffect(() => {
const height = ref.current.offsetHeight;
setHeight(height);
}, []);
✔ Prevents UI flicker
✔ Ensures layout is correct before paint
✅ When to Use useLayoutEffect()
✔ Measuring DOM size/position
✔ Synchronously updating layout
✔ Animations that depend on layout
✔ Preventing visual flicker
❌ When NOT to Use It
❌ Data fetching
❌ API calls
❌ Subscriptions
❌ Logging
❌ Anything not affecting layout
Use useEffect() instead.
🎯 Short Interview Answer
useLayoutEffect()runs synchronously after DOM updates but before the browser paints, making it ideal for DOM measurements and layout changes.useEffect()runs after paint and is non-blocking, so it’s better for side effects like API calls and subscriptions.
⭐ One-line Summary
useLayoutEffect is for layout-critical DOM work; useEffect is for everything else.