Sub topic 14
Prefetching data before it is needed
This chapter assumes you know query keys, staleTime, and gcTime, and that you can use useQuery and QueryClientProvider. Prefetching builds on the cache rules from the earlier chapters.
What prefetching does
Prefetching loads data into the cache before a component asks for it. When the component later calls useQuery with the same key, it finds cached data and renders at once. It doesn't have to show a loading state.
queryClient.prefetchQuery takes the same queryKey and queryFn options as useQuery. It never throws and returns a Promise that resolves with nothing. If the request fails, the error is not shown, and the real useQuery call retries later.
Prefetching on hover
A common use is a list of links. When the pointer enters a link, you start loading the detail data. By the time the user clicks, the data is often already cached.
import { useQuery, useQueryClient } from '@tanstack/react-query'
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()
}
const todoQuery = (id: number) => ({
queryKey: ['todos', id],
queryFn: () => fetchTodo(id),
staleTime: 60 * 1000,
})
export function TodoLink({ id, title }: { id: number; title: string }) {
const queryClient = useQueryClient()
return (
<a
href={`/todos/${id}`}
onMouseEnter={() => queryClient.prefetchQuery(todoQuery(id))}
>
{title}
</a>
)
}
export function TodoDetail({ id }: { id: number }) {
const { data } = useQuery(todoQuery(id))
return <p>{data?.title}</p>
}Both components use one shared todoQuery function. This keeps the key, the query function, and staleTime identical in both places. If they drift apart, the prefetch fills a cache entry that the component never reads.
Why staleTime matters here
prefetchQuery only fetches if the cached data is stale. With the default staleTime of 0, data is stale immediately. So when TodoDetail mounts, it renders the prefetched data but also starts a background refetch. Setting staleTime on the shared options, as above, avoids that extra request while the data is still fresh.
The prefetched entry also follows normal garbage collection. If no component uses it, it is removed after gcTime (5 minutes by default). Data prefetched too early may be gone before it is used.
The flow
Other places to prefetch
- Inside an event handler, as shown above.
- In a
useEffectwhen the user is likely to move to the next step, such as the next page of a list. - In a router loader, using
queryClient.ensureQueryDatato return cached data when it exists and fetch it only when it doesn't.
Common mistakes
- Using a different key in the prefetch and in
useQuery. - Forgetting
staleTime, which leads to a duplicate request right after the prefetch. - Prefetching too much data. Each prefetch costs a request, so limit it to likely next actions.
Exercise
You prefetch ['todos', 5] on hover with the default staleTime. The user clicks, and the detail page shows data immediately but also sends a second request. Why, and how do you stop it?
Show answer
With the default staleTime of 0, the prefetched data is stale as soon as it arrives. When useQuery mounts, it shows the cached data and refetches it in the background. Set a staleTime (for example 60 seconds) in the shared query options used by both prefetchQuery and useQuery.