Overview
Code splitting allows you to split your bundle into smaller chunks which can be loaded on demand. This reduces the initial bundle size and improves application load time. React provides built-in support for code splitting throughReact.lazy and dynamic imports.
React.lazy
React.lazy lets you render a dynamic import as a regular component. It automatically loads the bundle containing the component when it’s first rendered.
API Signature
Frompackages/react/src/ReactLazy.js:222:
Basic Usage
Route-Based Code Splitting
Split code by routes to load only the necessary code for each page:Component-Based Code Splitting
Named Exports
Lazy loading works with default exports. For named exports, create an intermediate module:Error Boundaries with Lazy Loading
Always wrap lazy components with error boundaries to handle loading failures:Advanced Loading States
Preloading Components
Preload components before they’re needed:Retry Logic
Implement retry logic for failed loads:Library Code Splitting
Split large libraries:Lazy Internal State Tracking
Frompackages/react/src/ReactLazy.js:25:
- Uninitialized (-1): Not yet loaded
- Pending (0): Currently loading
- Resolved (1): Successfully loaded
- Rejected (2): Failed to load
Webpack Magic Comments
Use webpack magic comments for better control:Multiple Lazy Components
Best Practices
- Split by routes first: Route-based splitting provides the best user experience
- Avoid too many splits: Each split adds network overhead
- Use appropriate loading states: Provide meaningful feedback during loading
- Implement error boundaries: Handle loading failures gracefully
- Preload strategically: Preload on hover or user intent signals
- Monitor bundle sizes: Use webpack-bundle-analyzer to track chunk sizes
- Test with slow networks: Ensure loading states work well on slow connections
Bundle Analysis
Analyze your bundles to identify splitting opportunities:Performance Considerations
- Initial load vs runtime: Balance between initial bundle size and runtime overhead
- Network requests: Each chunk requires a separate network request
- Cache invalidation: Properly configure caching headers for chunks
- Compression: Ensure chunks are properly compressed (gzip/brotli)
See Also
- Suspense - Loading states and boundaries
- Error Boundaries - Handling loading failures
- Concurrent Features - Advanced loading patterns