Sub topic 6
How the cache works: staleTime and gcTime
This chapter assumes you can write a basic useQuery call, know what a query key is, and have a QueryClientProvider set up. Here you will learn how TanStack Query decides whether to serve cached data, refetch it, or throw it away.
One cache, two timers
Every query result lives in the QueryClient cache, stored under its query key. Two settings control its life:
staleTimeis how long data counts as fresh after a successful fetch. The default is0, so data is stale immediately.gcTimeis how long an unused query stays in the cache before garbage collection removes it. The default is 5 minutes. A query is unused when no mounted component observes it.
These timers answer different questions. staleTime asks whether to refetch. gcTime asks whether to keep the data at all.
What happens when a component mounts
When a component mounts with a key that is already cached, the cached data is returned right away. The query then checks whether the data is stale:
- If it is fresh, no network request is made.
- If it is stale, the cached data is shown while a background refetch runs.
isFetchingistrue, butisPendingisfalse. - If the key is not in the cache, the query is
pendinguntil the first fetch finishes.
import { useQuery } 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()
}
function TodoDetail({ id }: { id: number }) {
const { data } = useQuery({
queryKey: ['todos', id],
queryFn: () => fetchTodo(id),
staleTime: 60 * 1000,
})
return <p>{data?.title}</p>
}The id in the key gives each todo its own cache entry. With staleTime set to one minute, remounting this component within 60 seconds reuses the cached todo and sends no request.
The life of a cache entry
The gcTime countdown starts only when the last component using the query unmounts. If a component mounts again before it ends, the countdown is cancelled and the cached data is reused.
Choosing values
| Data | Suggested `staleTime` | Reason |
|---|---|---|
| Live prices, notifications | `0` (default) | Must be current |
| User profile, todo list | 30 seconds to a few minutes | Changes occasionally |
| Country list, config | `Infinity` | Almost never changes |
Common errors
- Seeing a refetch on every mount and assuming the cache is broken. With the default
staleTimeof0, this is the expected behavior. The cache still shows old data instantly while it refetches. - Setting
gcTimelower thanstaleTime. The entry can be removed while it would still count as fresh, so you lose the benefit ofstaleTime. - Setting
gcTime: 0and wondering why back navigation shows a loading spinner. The data is removed as soon as the component unmounts. - Confusing
staleTimewith a polling interval. It never triggers a fetch by itself. It only changes how the next trigger, such as a mount, is treated.
Exercise
A query uses staleTime of 30 seconds and the default gcTime. A user opens a page that mounts the query, leaves after 10 seconds, and comes back 2 minutes later. What does the user see, and does a network request happen?
Show answer
The entry is still in the cache, because 2 minutes is less than the 5 minute gcTime. The cached data appears immediately. It became stale after 30 seconds, so a background refetch runs on mount, and the UI updates when it finishes.