useEffect() vs useLayoutEffect()
1. useEffect()
- Runs after the render is painted on the screen.
- Non-blocking → does not block the browser from painting UI.
- Best for:
- API calls
- Event listeners
- Logging
- Updating state asynchronously
✅ Example:
import React, { useState, useEffect } from "react";
function UseEffectExample() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("useEffect → runs after paint");
}, [count]);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default UseEffectExample;
2. useLayoutEffect()
- Runs synchronously after DOM mutations but before the browser paints.
- Blocking → it pauses the paint until the code inside finishes.
- Best for:
- Measuring DOM elements (
offsetHeight,scrollWidth) - Synchronous re-render adjustments
- Preventing flickering
- Measuring DOM elements (
✅ Example:
import React, { useState, useLayoutEffect, useRef } from "react";
function UseLayoutEffectExample() {
const [width, setWidth] = useState(0);
const boxRef = useRef();
useLayoutEffect(() => {
// Runs before paint → ensures correct size calculation
setWidth(boxRef.current.offsetWidth);
console.log("useLayoutEffect → runs before paint");
}, []);
return (
<div>
<div ref={boxRef} style={{ width: "200px", height: "50px", background: "lightblue" }}>
Box
</div>
<p>Box width: {width}px</p>
</div>
);
}
export default UseLayoutEffectExample;
🔹 Difference Table
| Feature | useEffect() 🟢 |
useLayoutEffect() 🔵 |
|---|---|---|
| Runs after render | ✅ Yes, after paint | ❌ No, runs before paint |
| Blocks browser paint? | ❌ No (async) | ✅ Yes (sync) |
| Use cases | API calls, event listeners, logging | DOM measurements, sync UI updates |
| Performance | Faster (non-blocking) | Can slow UI if heavy work inside |
| Flicker prevention | ❌ Not possible | ✅ Possible |
🔹 Key Takeaway
- Use
useEffectfor most side effects. - Use
useLayoutEffectonly when you need to measure DOM or prevent flickering. - Overusing
useLayoutEffectcan hurt performance.