useLayoutEffect runs synchronously after DOM mutations but before the browser paints. Here's when and how to use it.
useEffect vs useLayoutEffect
When to Use useLayoutEffect
DOM Measurements
Scroll Position
Animation Initialization
Focus Management
Canvas and WebGL
Third-Party Libraries
Server-Side Rendering
Performance Considerations
Custom Hooks with useLayoutEffect
Best Practices
When to Use useLayoutEffect:
✓ DOM measurements
✓ Scroll position management
✓ Preventing visual flicker
✓ Synchronous animations
✓ Third-party DOM libraries
When to Use useEffect:
✓ Data fetching
✓ Subscriptions
✓ Logging
✓ Any async operation
✓ Most side effects
Performance:
✓ Keep useLayoutEffect fast
✓ Avoid expensive computations
✓ Don't block with async code
✓ Prefer useEffect when possible
SSR:
✓ Use isomorphic version
✓ Handle client-only cases
✓ Suppress warnings appropriately
Conclusion
useLayoutEffect runs synchronously before the browser paints, making it essential for DOM measurements and preventing visual flicker. Use it sparingly for synchronous DOM operations like measuring elements, managing scroll position, or initializing animations. For most side effects, useEffect is the better choice as it doesn't block the browser. Remember to handle SSR cases with an isomorphic version.