React.lazy and Suspense enable code splitting for better performance. Here's how to use them effectively.
Basic Lazy Loading
Route-Based Code Splitting
Multiple Suspense Boundaries
Named Exports
Preloading Components
Error Handling
Conditional Loading
Modal/Dialog Loading
Skeleton Loading
Code Splitting Strategies
Webpack Magic Comments
Testing Lazy Components
Best Practices
When to Use:
✓ Route components
✓ Large components (>30KB)
✓ Conditionally rendered content
✓ Below-the-fold content
Suspense Boundaries:
✓ Group related components
✓ Place near lazy components
✓ Provide meaningful fallbacks
✓ Consider UX of loading states
Performance:
✓ Preload on hover/focus
✓ Use webpackPrefetch
✓ Combine related chunks
✓ Measure bundle sizes
Avoid:
✗ Over-splitting small components
✗ Single global Suspense
✗ Ignoring error boundaries
✗ Too many loading states
Conclusion
React.lazy and Suspense enable powerful code splitting for better initial load times. Use route-based splitting for page components, lazy load heavy components and modals, and provide meaningful loading states. Preload components on user interaction hints for better perceived performance. Always wrap lazy components with error boundaries for production reliability.