Skip to main content

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 through React.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

From packages/react/src/ReactLazy.js:222:
The function returns a lazy component:

Basic Usage

From packages/react/src/ReactLazy.js:204, the dynamic import must return an object with a default export:
Always use default exports for lazy-loaded components.

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:
Or use a dynamic re-export:

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

From packages/react/src/ReactLazy.js:25:
Lazy components track their loading state internally:
  • 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

  1. Split by routes first: Route-based splitting provides the best user experience
  2. Avoid too many splits: Each split adds network overhead
  3. Use appropriate loading states: Provide meaningful feedback during loading
  4. Implement error boundaries: Handle loading failures gracefully
  5. Preload strategically: Preload on hover or user intent signals
  6. Monitor bundle sizes: Use webpack-bundle-analyzer to track chunk sizes
  7. Test with slow networks: Ensure loading states work well on slow connections

Bundle Analysis

Analyze your bundles to identify splitting opportunities:

Performance Considerations

  1. Initial load vs runtime: Balance between initial bundle size and runtime overhead
  2. Network requests: Each chunk requires a separate network request
  3. Cache invalidation: Properly configure caching headers for chunks
  4. Compression: Ensure chunks are properly compressed (gzip/brotli)

See Also