The useLayoutEffect hook runs synchronously after DOM mutations but before the browser paints. Here's when and how to use it.
Basic Usage
vs useEffect
Tooltip Positioning
Auto-resize Textarea
Scroll Position Restoration
Focus Management
Animation Setup
Dynamic Width Measurement
Third-Party Library Integration
Window Resize Handler
SSR Considerations
Best Practices
When to Use:
✓ DOM measurements
✓ Preventing visual flicker
✓ Synchronous DOM mutations
✓ Focus management
vs useEffect:
✓ useLayoutEffect: visual updates
✓ useEffect: data fetching, subscriptions
✓ useLayoutEffect: blocks paint
✓ useEffect: non-blocking
Performance:
✓ Keep effects fast
✓ Avoid heavy computation
✓ Consider throttling resize
✓ Use useEffect when possible
Avoid:
✗ Data fetching
✗ Subscriptions (use useEffect)
✗ Long-running operations
✗ SSR without isomorphic check
Conclusion
The useLayoutEffect hook runs synchronously after DOM mutations but before paint, making it ideal for measurements and visual updates that must happen before the user sees the result. Use it sparingly for cases where useEffect would cause visual flicker. For most side effects, prefer useEffect to avoid blocking the browser.