Sub topic 14
Prefetching data before it is needed
This chapter assumes you can already write a useQuery call, choose query keys, and explain staleTime and gcTime. If the cache rules feel shaky, review them first, because prefetching is mostly an application of those rules.
What prefetching does
Prefetching means loading data into the query cache before any component has asked for it. When the user later opens the screen, useQuery finds the entry already in the cache and renders it without a loading state.
The cache is the mechanism. A prefetch runs the same fetch a useQuery would run, stores the result under a query key, and no component has to be mounted for this to work. The component that needs the data only has to use the same key.
Share the query definition
A prefetch only helps if it uses exactly the same key as the useQuery that follows. A typo or a different key shape creates a second cache entry, and the user still waits. Define the key and function once and reuse them. TanStack Query v5 provides queryOptions for this.
import { queryOptions } from '@tanstack/react-query'
export type Todo = { id: number; title: string; done: boolean }
async function fetchTodo(id: number): Promise<Todo> {
const res = await fetch(`/api/todos/${id}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function todoQueryOptions(id: number) {
return queryOptions({
queryKey: ['todos', id],
queryFn: () => fetchTodo(id),
staleTime: 60 * 1000,
})
}queryOptions returns the object unchanged at runtime. Its value is type inference: data from useQuery(todoQueryOptions(id)) and the value returned by getQueryData(todoQueryOptions(id).queryKey) both have the type Todo.
Prefetch on user intent
The most common trigger is hover or focus. A user who hovers a link has not committed to clicking it, but the odds are high, and the request usually finishes before the click completes.
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { todoQueryOptions } from './todo-queries'
export function TodoLink({
id,
title,
onOpen,
}: {
id: number
title: string
onOpen: (id: number) => void
}) {
const queryClient = useQueryClient()
const prefetch = () => {
void queryClient.prefetchQuery(todoQueryOptions(id))
}
return (
<button onMouseEnter={prefetch} onFocus={prefetch} onClick={() => onOpen(id)}>
{title}
</button>
)
}
export function TodoDetail({ id }: { id: number }) {
const { data, isPending } = useQuery(todoQueryOptions(id))
if (isPending) return <p>Loading...</p>
return <p>{data?.title}</p>
}Handling onFocus as well as onMouseEnter gives keyboard users the same benefit.
How prefetchQuery decides whether to fetch
prefetchQuery follows the staleness rules you already know:
- If no entry exists for the key, it fetches.
- If an entry exists and is still fresh according to
staleTime, it does nothing. - If an entry exists and is stale, it fetches again.
This is why the staleTime: 60 * 1000 in the shared options matters. The default staleTime is 0, so every entry counts as stale immediately. Without a staleTime, each mouse-over would trigger a new request. You can also pass staleTime directly to prefetchQuery to override the shared value for one call.
Two more behaviors are easy to miss:
prefetchQueryreturns aPromise<void>, and it never rejects. If the fetch fails, the error is swallowed and no data is stored. The lateruseQuerythen fetches normally and reports its own error state.- A prefetched entry has no observers, so it follows the
gcTimerule. It is removed aftergcTime(5 minutes by default) unless a component subscribes first. Prefetching something the user opens ten minutes later gains nothing.
ensureQueryData for loaders
prefetchQuery is fire-and-forget. Sometimes you need the data, or you need to know it failed. A route loader is the typical case: the router should wait for the data before showing the page. For that, use ensureQueryData.
import type { QueryClient } from '@tanstack/react-query'
import { todoQueryOptions } from './todo-queries'
export async function todoRouteLoader(queryClient: QueryClient, id: number) {
return queryClient.ensureQueryData(todoQueryOptions(id))
}The differences from prefetchQuery are:
| Behavior | `prefetchQuery` | `ensureQueryData` |
|---|---|---|
| Returns | `Promise<void>` | `Promise<data>` |
| On fetch error | Swallowed | Promise rejects |
| Cached but stale entry | Refetches | Returns the cached data without fetching |
| No entry | Fetches | Fetches |
Because ensureQueryData returns stale data as is, it suits "make sure something is there" cases. If you need fresh data, use prefetchQuery or fetchQuery, or pass revalidateIfStale: true to ensureQueryData.
Seeding the cache from data you already have
Sometimes you do not need a second request at all. A list endpoint often returns objects that contain most of what the detail screen shows. You can write those objects into the detail keys with setQueryData when the list loads.
import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { Todo } from './todo-queries'
export function TodoList() {
const queryClient = useQueryClient()
const { data } = useQuery({
queryKey: ['todos'],
queryFn: async (): Promise<Todo[]> => {
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
const todos: Todo[] = await res.json()
todos.forEach((todo) => queryClient.setQueryData(['todos', todo.id], todo))
return todos
},
})
return <p>{data?.length ?? 0} todos loaded</p>
}Use this only when the list items have the same shape as the detail response. If the detail endpoint returns extra fields, seeded entries would show incomplete data as if it were complete. In that case, pass the list item as placeholderData or initialData on the detail query instead. The detail query can then still fetch the full record.
Note also that setQueryData marks the entry as freshly updated. With a non-zero staleTime, the detail query will not refetch for that period.
Prefetching other query types
queryClient.prefetchInfiniteQuery works like prefetchQuery for useInfiniteQuery. It needs initialPageParam, and pages controls how many pages to load. The key must match the one used by the later useInfiniteQuery, and so must the page-param logic.
Prefetching can also happen during render, so that two requests start in parallel. Calling useQuery in a parent for data that only a child displays is a simple version of this. It avoids the waterfall where the child's fetch starts only after the child mounts.
Common mistakes
- Mismatched keys.
['todo', 7]and['todos', 7]are different entries. Share options objects to avoid this. - Forgetting
staleTime. With the default of 0, a prefetched entry is stale when the component mounts.useQuerythen shows the cached data immediately but also starts a background refetch. This is not a bug, but it makes the prefetch less useful than it looks. - Prefetching too much. Prefetching every link on a page costs bandwidth and server load. Limit it to likely next steps, such as the hovered item or the next page.
- Relying on prefetch for error handling. A failed prefetch is silent. Handle errors in
useQuery, or useensureQueryDatawhen failure must stop navigation.
Exercise
A list of todos prefetches each todo's detail on hover with queryClient.prefetchQuery({ queryKey: ['todos', id], queryFn: () => fetchTodo(id) }). The detail page uses useQuery({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) }). The user still sees "Loading..." after hovering. Give two separate problems and a fix for each.
Show answer
First, the keys differ: the prefetch writes to ['todos', id] but the page reads ['todo', id], so the page never finds the prefetched entry. Fix this by building both from one shared queryOptions function. Second, neither call sets staleTime, so it is 0 and any prefetched entry is stale immediately. Once the keys match, the page would show the cached data but still refetch in the background, and repeated hovers would trigger repeated requests. Fix this by setting a staleTime such as 60 seconds in the shared options.
Exercise
A route loader must show an error page if the todo cannot be loaded, and it must not refetch a todo that is already in the cache. Which method should it call, prefetchQuery or ensureQueryData, and why?
Show answer
ensureQueryData. It returns cached data without fetching, even if that data is stale, and its promise rejects when the fetch fails, so the loader can send the user to an error page. prefetchQuery swallows errors and would refetch stale entries.