Code Splitting
Code splitting breaks your application into smaller chunks that are loaded on-demand, reducing initial bundle size and improving performance. TanStack Router provides automatic and manual code splitting strategies.Overview
Code splitting benefits:- Faster initial page loads
- Reduced bundle size
- On-demand loading of route components
- Better caching and performance
- Automatic with file-based routing
Automatic Code Splitting
With file-based routing, TanStack Router automatically code-splits your routes when you enable the plugin:vite.config.ts
Manual Code Splitting
For code-based routing, use the.lazy() method:
Basic Lazy Routes
src/main.tsx
src/posts.lazy.tsx
File-Based Lazy Routes
With file-based routing, create.lazy.tsx files:
src/routes/posts.tsx
src/routes/posts.lazy.tsx
Lazy Route Components
UselazyRouteComponent for component-level splitting:
PostsComponent.tsx
Preloading Routes
Preload routes before navigation:Intent-Based Preloading
Preload when user shows intent to navigate:Viewport Preloading
Preload when links enter viewport:Manual Preloading
Preload specific routes programmatically:Link Preloading
Control preloading per link:Loading States
Show loading UI while lazy components load:Suspense Boundaries
Wrap lazy routes in Suspense for better UX:src/routes/__root.tsx
Bundle Analysis
Analyze your bundle to identify optimization opportunities:vite.config.ts
Lazy Loading Libraries
Split large dependencies:Dynamic Imports
Use dynamic imports for conditional features:Code Splitting Strategies
Route-Level Splitting
Split by route (recommended):Feature-Level Splitting
Split by feature within routes:Best Practices
Route-Based Splitting
Split at route boundaries for maximum benefit
Preload Intelligently
Use intent-based preloading for likely navigation paths
Show Loading States
Always provide feedback while chunks load
Measure Impact
Use bundle analysis to verify splitting effectiveness
Balance: Too much splitting can hurt performance with many HTTP requests. Find the right balance for your app.
Performance Tips
- Split heavy routes: Focus on routes with large dependencies
- Preload critical routes: Preload likely navigation targets
- Use suspense: Provide loading feedback
- Analyze bundles: Regularly check chunk sizes
- Cache aggressively: Set proper cache headers for chunks
Troubleshooting
Chunks not splitting
- Verify
autoCodeSplitting: truein plugin config - Check that components use
lazy()orlazyRouteComponent() - Ensure dynamic imports use
import()notrequire()
Slow chunk loading
- Enable preloading for frequently accessed routes
- Use CDN for faster chunk delivery
- Check network waterfall in DevTools
Next Steps
SSR
Combine code splitting with server-side rendering
Scroll Restoration
Maintain scroll position across lazy-loaded routes