Skip to main content
Prefetching allows you to fetch data before it’s actually needed, creating instant loading experiences for your users.

Basic Prefetching

Use queryClient.prefetchQuery() to prefetch data:

When to Prefetch

On Hover

Prefetch when user hovers over a link:

On Focus

Prefetch when user focuses on an input:

On Route Change

Prefetch data for the next page in pagination:

On Mount

Prefetch related data when component mounts:

Prefetch with staleTime

Prevent refetching data that’s already fresh:
Setting staleTime in prefetch prevents unnecessary network requests if the data is already in cache and fresh.

Prefetching Infinite Queries

Prefetch the first page of an infinite query:

Router Integration

React Router

TanStack Router

Next.js App Router

Prefetch in Server Components:

Prefetch vs ensureQueryData

prefetchQuery

Fires and forgets - doesn’t return data:

ensureQueryData

Returns the data, waits if needed:
Use ensureQueryData when you need the data immediately:

Prefetching Multiple Queries

Prefetch several queries in parallel:

Conditional Prefetching

Only prefetch under certain conditions:

Prefetching from Query Data

Use existing query data to prefetch related queries:
Use setQueryData instead of prefetchQuery when you already have the data. It’s instant and doesn’t require a network request.

Background Prefetching

Prefetch data in the background while user is idle:

Debounced Prefetching

Debounce prefetch calls to avoid excessive requests:

Prefetch with Custom Hook

Create a reusable prefetch hook:

Best Practices

  1. Set appropriate staleTime - Prevent refetching fresh data
  2. Prefetch on user intent - Hover, focus, route changes
  3. Use ensureQueryData when you need the data immediately
  4. Don’t over-prefetch - Balance UX with bandwidth usage
  5. Prefetch in parallel when possible
  6. Consider user’s connection - Maybe skip prefetch on slow connections

Next Steps