Sub topic 6
How the cache works: staleTime and gcTime
This chapter assumes you can write a basic useQuery call, you know what a query key is, and you have a QueryClientProvider set up. You do not need anything beyond that. By the end you should be able to predict, for any query, whether a component will get cached data, trigger a network request, or both.
One cache, two timers
TanStack Query keeps every result in a single in-memory cache owned by the QueryClient. Each entry is stored under its query key. Two settings control what happens to an entry over time:
| Option | Question it answers | Default |
|---|---|---|
| `staleTime` | How long is the data considered fresh? | `0` (stale immediately) |
| `gcTime` | How long does an unused entry stay in memory? | 5 minutes |
These timers are independent and they act on different things. staleTime decides whether the cached data should be refetched. gcTime decides whether the cached data still exists.
Fresh and stale
A query is fresh while less than staleTime has passed since the last successful fetch. Once that time has passed, the query is stale. Stale data is still returned from the cache and still rendered. "Stale" only means the library is allowed to check the server again.
With the default staleTime of 0, data is stale the instant it arrives. That is why a new component using an already-cached key shows the cached data right away and also fires a background request.
A fresh query does not refetch on its own triggers. A stale query does. The triggers are:
- a new component mounts and uses the query
- the browser window regains focus
- the network reconnects
- you call
invalidateQueries(this marks the query stale and refetches active ones)
The next chapter covers these triggers in detail. For now, remember the rule: triggers only cause a refetch when the data is stale.
gcTime and inactive queries
A query is active while at least one mounted component observes it. When the last observer unmounts, the query becomes inactive. It stays in the cache, and a gcTime countdown starts. If a component subscribes to the same key before the countdown ends, the timer is cancelled and the cached data is reused. If it ends first, the entry is removed, and the next use starts from pending with no data.
The diagram shows these states.
Setting the timers
You can set the options on one query:
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function Todos() {
const { data, isFetching } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
staleTime: 30 * 1000, // fresh for 30 seconds
gcTime: 10 * 60 * 1000, // keep unused data for 10 minutes
})
return (
<div>
{isFetching && <small>Updating...</small>}
<ul>
{data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
)
}Or you can set app-wide defaults when you create the client. Individual queries still override them.
import { QueryClient } from '@tanstack/react-query'
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
gcTime: 15 * 60 * 1000,
},
},
})In v5, gcTime replaced the old name cacheTime. If you copy code from an older article that uses cacheTime, rename it.
Walking through a timeline
Suppose ['todos'] has staleTime: 30000 and the default gcTime of 5 minutes. A user opens a page with the list, leaves, and comes back.
| Time | Event | What happens |
|---|---|---|
| 0:00 | `Todos` mounts | No entry exists. Status is `pending`, and a request runs. |
| 0:01 | Response arrives | Data is cached and fresh until 0:31. |
| 0:10 | User leaves, `Todos` unmounts | The entry is inactive. The 5-minute `gcTime` countdown starts. |
| 0:20 | User returns, `Todos` mounts | Entry is still fresh. Data shows instantly. No request. |
| 0:25 | User leaves again | Inactive again. A new `gcTime` countdown starts. |
| 1:00 | User returns | Entry is stale. Cached data shows instantly, and a background refetch runs. |
At 1:00 the component sees data immediately and isFetching is true while the refetch runs. isPending is false, because data exists. This difference between isPending and isFetching is why users see cached screens without spinners.
Special values
staleTime: Infinitymeans the data never becomes stale on its own. Use it for data that changes only when you change it, and refresh it withinvalidateQueries.gcTime: Infinitydisables garbage collection, so entries stay until the page reloads. Be careful with queries whose keys vary a lot, such as search terms, because the cache will grow without limit.gcTime: 0removes data as soon as nothing uses it. Every remount then starts frompending.- In v5,
staleTimecan also be a function that receives the query and returns a number. This helps when freshness depends on the data itself.
Common errors
Expecting staleTime to delete data. Stale data is not removed. It stays in the cache and keeps being served. Only gcTime removes entries, and only inactive ones.
Leaving staleTime at 0 and wondering about duplicate requests. If three components mount in a row using the same key, the first request is shared. Components that mount after it finishes see stale data and start another refetch. Setting a staleTime of even a few seconds stops this churn.
Setting gcTime shorter than staleTime. After the entry is removed, the freshness information is gone too. The user sees a loading state instead of fresh cached data. Keep gcTime at least as long as staleTime.
Confusing the two timers when debugging. If data keeps refetching, look at staleTime. If data keeps disappearing and showing a spinner, look at gcTime.
Changing a value but not the key. If a request depends on a variable, such as a user id, that variable must be in the query key. Otherwise two different requests share one cache entry, and the timers apply to the wrong data.
Exercises
Exercise
A query uses staleTime: 5 * 60 * 1000 and the default gcTime. A user visits a page, leaves it after 1 minute, and returns 2 minutes later. Does a request happen? What if they return 20 minutes later?
Show answer
After 2 minutes away, the entry is inactive but not yet collected (5-minute default gcTime), and the data is only 3 minutes old, so it is still fresh. The cached data shows and no request runs. After 20 minutes the entry was collected after 5 minutes of being unused, so the component starts from pending and makes a new request.
Exercise
A list screen shows a spinner every time the user navigates back to it, even though the data was loaded a minute earlier. The query uses gcTime: 0. What is the cause, and how would you change it so cached data shows instantly?
Show answer
With gcTime: 0 the entry is removed as soon as the component unmounts, so each visit starts with no data and a pending status. Raise gcTime (for example to the default 5 minutes). Also set a staleTime if you want to avoid the background refetch on return.