Lazy Route Discovery
Lazy route discovery enables you to load route definitions dynamically, reducing initial bundle size and improving performance.Overview
React Router supports two levels of lazy loading:- Lazy route modules (
route.lazy) - Load route properties (loader, component, etc.) - Lazy route discovery (
patchRoutesOnNavigation) - Discover and add routes dynamically
Lazy Route Modules
Uselazy() to load route properties on demand:
Immutable Properties
Some properties cannot be loaded lazily:path- Needed for matchingindex- Needed for matchingcaseSensitive- Needed for matchingid- Needed to identify the routechildren- Needed for route hierarchy
Static Properties
You can define properties statically and supplement with lazy loading:lazy().
Route Discovery with patchRoutesOnNavigation
Discover and add routes dynamically during navigation:The patch Function
routeId: Parent route ID, ornullfor rootroutes: Array of routes to add
Eager Discovery (Framework Mode)
In framework mode with RSC, routes can be discovered eagerly:Manifest Pattern
Load route manifests for efficient discovery:Component vs element
UseComponent with lazy routes instead of element:
Interruptions
If a navigation is interrupted whilelazy() is loading, React Router still calls the returned handler to maintain consistency:
SSR Hydration
When server-rendering with lazy routes, preload them before hydration:HMR Support
Lazy routes work seamlessly with Hot Module Replacement during development:Benefits
- Smaller bundles: Only load code when needed
- Faster initial load: Reduce time to interactive
- Code splitting: Automatic via dynamic imports
- Progressive enhancement: Routes work before JS loads (with SSR)
Best Practices
- Lazy load large sections: Dashboard, admin, settings
- Keep critical routes static: Home, 404, layout
- Use route.lazy for components: Avoid lazy() for just loaders
- Preload on hover: Improve perceived performance
- Cache manifests: Don’t re-fetch route definitions