React
useEffect vs useLayoutEffect
useEffectanduseLayoutEffectdiffer in execution timing, not purpose.useLayoutEffectis executed synchronously before paint and can block visual updates.useEffectis executed after paint and never blocks what the user sees.
useEffect
- Executed after render
- Executed after commit and paint
- Does not block render
- Does not block paint
- Used for:
- data fetching
- subscriptions
- logging
- non-visual side effects
Even with heavy synchronous code, the UI is already displayed.
useLayoutEffect
- Executed after render
- Executed after DOM mutations
- Executed before paint
- Does not block render
- Blocks paint while executing
- Intended for:
- DOM measurements
- synchronous layout reads (
getBoundingClientRect) - DOM correction before the first display
Heavy logic here causes jank.
Phase Order
- Render phase
- Commit phase
- DOM mutations
useLayoutEffect
- Paint
useEffect
Practical Rule
- Default →
useEffect useLayoutEffect— only when necessary- If there is no work with layout —
useLayoutEffectis an error
Short Answer for Interview
useLayoutEffect is executed synchronously before paint and can block visual updates, while useEffect is executed after paint and does not affect what the user sees.