Skip to main content

Code Splitting

Code splitting breaks your application into smaller chunks that load on demand, improving initial load time and overall performance.

Automatic Code Splitting

React Router automatically code-splits when you use lazy():
The dashboard route only loads when the user navigates to /dashboard.

Framework Mode

In framework mode, routes are automatically code-split by default:
Each route file becomes its own chunk:

Manual Code Splitting

Route Components

Split components with React.lazy() and Suspense:

Utility Functions

Split heavy utilities:

Third-Party Libraries

Lazy load large dependencies:

Preloading

Improve perceived performance by preloading routes:

Chunk Optimization

Shared Chunks

Extract common dependencies:

Dynamic Import Names

Name your chunks for better debugging:

Bundle Analysis

Visualize Bundle Size

Check Chunk Sizes

Loading States

Route Level

Show loading UI during route transitions:

Component Level

Handle component-level loading:

Error Boundaries

Handle chunk loading failures:

Performance Tips

  1. Split by route: Most effective code splitting strategy
  2. Split heavy components: Charts, editors, maps
  3. Don’t over-split: Too many chunks increases overhead
  4. Preload critical routes: On app startup or hover
  5. Monitor bundle size: Use visualization tools
  6. Cache aggressively: Set long cache headers for chunks

Framework Mode Optimizations

Route Groups

Group related routes:

Shared Layouts

Layouts are shared across child routes (not duplicated):

Best Practices

  1. Start with routes: Automatic splitting per route
  2. Add component splitting: For heavy UI components
  3. Profile before optimizing: Use React DevTools Profiler
  4. Test on slow networks: Ensure good UX during loading
  5. Monitor real-world metrics: Track bundle sizes in CI

Common Pitfalls

Splitting too aggressively
Split heavy features
Forgetting Suspense
Wrap with Suspense