Home
React
useLayoutEffect() for Layout Effects
July 26, 2025
1 min

Table Of Contents

01
useEffect vs useLayoutEffect
02
Use useLayoutEffect?
03
Real-World Use Cases

The useLayoutEffect hook runs after the DOM has been updated but before the browser has had a chance to paint the screen. This means you can make your measurements and then render the UI with the correct measurements before the user sees anything.

example
example

useEffect vs useLayoutEffect

HookTimingBlockingBest For
useEffectAfter paint❌ Non-blockingData fetching, subscriptions
useLayoutEffectBefore paint✅ BlockingLayout reads/writes, DOM sync
useLayoutEffect(() => {
// your layout-effect code here.
// this is where you read/write layout synchronously
// e.g. measure DOM, set position, prevent flicker
doLayoutThing()
return function cleanup() {
// clean up layout-related side-effects
// e.g. remove observers, cancel animations
doSomeCleanup()
}
}, [
// this is where dependencies of your useLayoutEffect callback go
// any value used inside the effect should be listed here
dep1,
dep2,
])

Use useLayoutEffect?

Use it when you need to:

1. Measure DOM before paint

useLayoutEffect(() => {
const height = ref.current.offsetHeight;
setHeight(height);
}, []);

2. Synchronize scroll or position

useLayoutEffect(() => {
window.scrollTo(0, savedPosition);
}, []);

Real-World Use Cases

✔ Tooltip positioning
✔ Virtualized lists
✔ Sticky headers
✔ Canvas & chart rendering

❌ Using it for data fetching
❌ Using it without real layout dependency


Tags

#ReactTesting

Share

Related Posts

React Fundamentals
useDeferredValue() for Responsive Inputs
July 30, 2025
1 min
© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube