TL;DR: TanStack Router supports automatic code splitting per route and multiple preloading strategies: hover-based, viewport-based, and programmatic. This guide covers lazy loading route components, preloading on link hover, cache management for preloaded routes, and measuring preloading effectiveness.
Introduction
As your SaaS application grows, so does your JavaScript bundle. A naive setup loads all routes upfront, which slows initial page load. TanStack Router supports automatic code splitting: each route's component and loader code is a separate chunk, loaded only when needed.
Combined with preloading, you can start loading a route's code and data before the user clicks, making navigation feel instant.
Code Splitting with Lazy Loading
// src/routes/dashboard.tsx
import { createFileRoute, lazyRouteComponent } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard')({
component: lazyRouteComponent(() => import('./dashboard.component')),
loader: () => import('./dashboard.loader').then(m => m.loadDashboardData),
})
Each route file becomes a separate chunk in your build output. TanStack Router handles the loading state automatically.
Hover-Based Preloading
import { Link } from '@tanstack/react-router'
function NavLink({ to, children }: { to: string; children: React.ReactNode }) {
const router = useRouter()
return (
<Link
to={to}
onMouseEnter={() => router.preloadRoute({ to })}
onTouchStart={() => router.preloadRoute({ to })}
>
{children}
</Link>
)
}
Preloading Strategies
| Strategy | Trigger | Best For | Cost |
|---|---|---|---|
| Hover-based | Mouse enter | Desktop navigation | Low |
| Viewport-based | Intersection Observer | Below-fold links | Medium |
| Programmatic | After page load | Next likely page | Low |
| All routes | On app mount | Small apps | High |
| Predictive | ML-based prediction | Large apps | Very high |
Measuring Preloading Effectiveness
Track how often preloaded routes are actually visited:
router.subscribe('onResolved', (event) => {
if (event.wasPreloaded) {
analytics.track('navigation_preloaded', { to: event.to })
}
})
Conclusion
Route preloading and code splitting in TanStack Router give you fast initial loads and instant navigation. The hover-based preloading strategy provides the best balance of performance improvement and bandwidth cost.
For more routing patterns, see TanStack Router Advanced Patterns. Combine code splitting with JavaScript Bundle Splitting Patterns for finer-grained chunk control. Measure your improvements against the Core Web Vitals Optimization Guide, and use Performance Budgeting for SaaS to prevent regressions.