Sub topic 12
Query keys, caching, and stale data
This chapter assumes you can write a component that fetches with useQuery (covered in the previous chapter), and that you know promises, useState, and basic HTTP. It explains how TanStack Query decides what to cache, when cached data counts as out of date, and when it fetches again.
Query keys identify data
Every query has a queryKey, an array that names the data it loads. TanStack Query uses the key as the address in its cache. Two components that call useQuery with equal keys share one cache entry and, in most cases, one network request.
import { useQuery } from '@tanstack/react-query';
async function fetchUser(userId, signal) {
const response = await fetch(`/api/users/${userId}`, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
function UserName({ userId }) {
const { data, error, isPending } = useQuery({
queryKey: ['user', userId],
queryFn: ({ signal }) => fetchUser(userId, signal),
});
if (isPending) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <span>{data.name}</span>;
}Keys are compared by value, not by reference. ['user', 1] written in two different files is the same key. Object properties are compared regardless of their order, so ['users', { page: 1, sort: 'name' }] equals ['users', { sort: 'name', page: 1 }]. Array order does matter: ['user', 1] and [1, 'user'] are different keys.
The key must include every input
The query function reads userId, so userId belongs in the key. When userId changes, the key changes, and the library looks up (or fetches) the entry for the new key. This replaces the dependency array from the useEffect version. It also removes the race condition from earlier chapters: each key has its own entry, so a slow response for user 1 cannot overwrite the data for user 2.
The most common mistake is leaving an input out of the key:
// Bug: userId is used by the function but is not part of the key.
useQuery({
queryKey: ['user'],
queryFn: ({ signal }) => fetchUser(userId, signal),
});Every user now shares the entry ['user'], so the component can show the wrong person's data. Treat the key like a dependency array: anything the query function uses to decide what to request should appear in the key.
The cache and its two timers
A cache entry moves through states controlled by two settings. They are easy to confuse.
staleTimeis how long fresh data stays fresh. Default:0milliseconds, so data is stale immediately.gcTimeis how long an entry with no observers stays in memory before it is garbage collected. Default: 5 minutes. (Older versions called thiscacheTime.)
An observer is a mounted component that uses the query. While at least one observer exists, the entry is kept. When the last one unmounts, the gcTime countdown begins. If a component asks for the key again before the countdown ends, the entry is reused.
diagram mermaidThe block above is not valid on its own, so here is the lifecycle as a proper diagram:
Stale does not mean wrong
"Stale" means "worth checking again", not "invalid". Stale data is still returned immediately from the cache. The library then refetches in the background and swaps in the new result if it differs. This pattern is called stale-while-revalidate.
The result is that a user who returns to a page sees the previous data at once, with no spinner, and then sees an update a moment later if anything changed.
Two status flags let you distinguish the cases:
isPendingis true when there is no data yet for this key.isFetchingis true whenever a request is in flight, including background refetches.
function UserBadge({ userId }) {
const { data, isPending, isFetching } = useQuery({
queryKey: ['user', userId],
queryFn: ({ signal }) => fetchUser(userId, signal),
staleTime: 60 * 1000,
});
if (isPending) return <p>Loading...</p>;
return (
<span style={{ opacity: isFetching ? 0.6 : 1 }}>{data.name}</span>
);
}Showing a full spinner only on isPending and a subtle hint on isFetching keeps the page stable during background updates.
When a refetch happens
A stale query refetches when one of these triggers fires:
| Trigger | Default | Option to change it |
|---|---|---|
| A new component mounts using the key | on | `refetchOnMount` |
| The browser window regains focus | on | `refetchOnWindowFocus` |
| The network reconnects | on | `refetchOnReconnect` |
| A fixed interval passes | off | `refetchInterval` |
| You call `invalidateQueries` | manual | not applicable |
Fresh data is never refetched by the first three triggers. That is the reason staleTime matters. With the default 0, every mount and every window focus causes a request. For data that changes rarely, such as a list of countries, a long staleTime removes almost all of that traffic.
Choosing a staleTime
There is no universal value. Use these questions:
- How bad is it if the user sees data that is a minute old? For a stock ticker, very bad. For a profile page, not at all.
- Does the user change this data themselves? If so, mutations and invalidation (next chapter) can keep it correct, which allows a longer
staleTime. - Is the request expensive for the server? A longer
staleTimecuts load.
staleTime: Infinity means the data is never considered stale. It will only refetch if you invalidate it or the entry is garbage collected and requested again.
You can set defaults once for the whole app on the QueryClient:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30 * 1000,
},
},
});
export function App({ children }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}Create the QueryClient outside the component, or keep it in a ref or state. If you create it inside the render body, every render makes a new, empty cache.
Deduplication
If three components mount in the same render pass and all call useQuery with ['user', 1], only one request is sent. Each component receives the same result. In an effect-based approach you would need to build this sharing yourself, which is one of the limits discussed earlier in the tutorial.
Deduplication applies only to in-flight requests and fresh data. If the data is stale and a new component mounts after the first request finishes, a new background refetch starts.
Hierarchical keys
Because keys are arrays, you can structure them from general to specific:
['users'] // the list of users
['users', { page: 2 }] // one page of the list
['user', 7] // one user
['user', 7, 'posts'] // posts written by user 7Methods that act on the cache, such as invalidateQueries, match keys by prefix. Invalidating ['user', 7] also marks ['user', 7, 'posts'] as stale. Planning your key layout early lets you refresh a whole group of related queries with one call.
Common errors
- Missing input in the key. Described above. Symptom: data does not change when props change, or the wrong data appears.
- Unstable keys. A key containing a value that changes every render, such as
Date.now()or a new object holding a fresh function, creates a new cache entry on every render and fetches endlessly. Keep keys to plain, serializable values. - Confusing
staleTimewithgcTime. RaisinggcTimedoes not stop refetching. It only keeps unused entries around longer. RaisingstaleTimeis what reduces requests. - Setting
gcTimebelowstaleTime. The entry may be removed while the data would still have counted as fresh. - Expecting a spinner on every refetch.
isPendingis false once data exists. UseisFetchingto show background activity.
Exercise
A component calls useQuery with queryKey ['products'] and a query function that fetches /api/products?category=${category}. The category prop changes from "shoes" to "hats", but the page keeps showing shoes. What is wrong, and how do you fix it?
Show answer
The key does not include category, so both categories share one cache entry and the library sees no reason to fetch again. Add the input to the key, for example queryKey: ['products', category]. Each category then gets its own entry, and changing the prop selects or fetches the right one.
Exercise
You set staleTime to 5 minutes. A user opens a profile, leaves the page for 2 minutes, then returns. Does a network request happen? What if they return after 10 minutes, and what do they see on screen while it loads?
Show answer
After 2 minutes the data is still fresh, so the cached data is shown and no request is sent. After 10 minutes the data is stale, so the cached data is shown immediately (provided the entry has not been garbage collected, which takes 5 minutes after the last component unmounts by default) and a background refetch runs. If the entry was garbage collected, isPending is true and a loading state appears until the response arrives.