React Hooks Series
useLayoutEffect
Identical to useEffect but fires synchronously after React updates the DOM — before the browser has had a chance to paint. Use it when you need to read layout or prevent a visual flicker.
01 — The difference
01
Execution order// Order of execution on mount:
// 1. React renders JSX → updates DOM
// 2. useLayoutEffect fires ← synchronous, blocks paint
// 3. Browser paints the screen
// 4. useEffect fires ← async, after paintBecause
useLayoutEffect blocks painting, avoid long-running work inside it. Use it only for DOM measurements and synchronous mutations that must happen before the user sees anything.02
When to use useLayoutEffect| Use useLayoutEffect | Use useEffect |
|---|---|
| Reading DOM dimensions (getBoundingClientRect) | Data fetching |
| Preventing layout flicker on initial render | Subscriptions & event listeners |
| Synchronising animations with DOM state | Timers & intervals |
02 — Live demo
↓
LayoutEffectTutorial — interactiveuseLayoutEffect reads the input value before useEffect sets it to "HELLO". The execution log shows the order clearly.
Execution log
useLayoutEffect fires before the browser paints — it read the empty value before useEffect set "HELLO"
Next: useImperativeHandle — expose a custom API from a child component to its parent via ref.