What’s the Difference Between useEffect
and useLayoutEffect
in React?
React provides two hooks to handle side effects:
useEffect
useLayoutEffect
Both are used to run code after a render, but they differ in when they execute and how they affect rendering performance.
Let’s break it down clearly.
useEffect
– Runs After Painting the Screen
useEffect
is asynchronous. It runs after the DOM has been painted, meaning the browser has already displayed your component.
Use When
- You want to perform non-blocking side effects
- You don’t need to measure the layout or manipulate the DOM before the user sees it
Example
useEffect(() => {
console.log('Runs after paint');
}, []);
Use case: API calls, analytics, event listeners, updating localStorage
useLayoutEffect
– Runs Before Painting the Screen
useLayoutEffect
is synchronous. It runs after React renders the DOM but before the browser paints it, blocking the screen until it's done.
Use When
- You need to measure or manipulate the DOM layout
- You must avoid visual flickers before the user sees the UI
Example
useLayoutEffect(() => {
const height = ref.current.offsetHeight;
console.log('Measured before paint:', height);
}, []);
Use case: DOM measurements, scroll positioning, animations, fixing layout shifts
Comparison Table: useEffect
vs useLayoutEffect
Feature |
useEffect |
useLayoutEffect |
Runs After Paint? |
? Yes |
? No |
Blocking UI Render? |
? No |
? Yes (can cause delay) |
Ideal for |
Async tasks, API calls |
DOM measurements, animations |
Performance Impact |
Minimal |
Can block rendering |
Runs in Node.js (SSR)? |
? Yes |
? No (not supported) |
When Not to Use useLayoutEffect
- If your side effect doesn't involve layout or sync DOM updates, prefer
useEffect
.
- Overusing
useLayoutEffect
can hurt performance because it blocks the browser from painting.
Visual Explanation (Optional Add-On)
[Render Phase] ? [DOM Commit] ?
- useLayoutEffect fires (sync)
- Browser paints screen
- useEffect fires (async)
Conclusion
Use useEffect
for
- Network requests
- Logging
- Side effects that don't need DOM measurement
Use useLayoutEffect
for:
- DOM reads (e.g., sizes, positions)
- Preventing layout flickers
- Synchronous UI adjustments before paint
Pro Tip: Start with useEffect
. If your layout or animation breaks visually, then try useLayoutEffect
.