Route Prefetching
Problem
Every navigation triggers loading spinners as code and data are fetched, making the application feel sluggish. Users wait for resources that could have been loaded during idle time, especially frustrating for predictable navigation patterns like pagination or common workflows.
Solution
Load code and data for likely next routes before users navigate to them. This makes transitions feel instant by preparing resources in advance.
Example
This example demonstrates prefetching product data when users hover over a link, so the data is ready instantly when they click.
// Prefetch route data on link hover
<Link
to="/products/123"
// Start loading data when user hovers (before click)
onMouseEnter={() => {
queryClient.prefetchQuery(['product', '123'], () =>
fetch('/api/products/123').then(r => r.json())
);
}}
>
View Product
</Link>
Benefits
- Makes navigation feel instant by having code and data ready before clicks.
- Improves perceived performance without affecting initial load time.
- Reduces or eliminates loading states during navigation.
- Uses idle time productively to prepare for likely user actions.
Tradeoffs
- Wastes bandwidth and resources if users don’t navigate to prefetched routes.
- Can slow down current page if prefetching competes for resources.
- Requires predicting which routes users are likely to visit next.
- May prefetch stale data if content changes between prefetch and navigation.