Sub topic 12
Query keys, caching, and stale data
This chapter assumes you can write a basic useQuery call, as shown in the previous chapter. You should also know what a React component re-render is. Here you will learn how query keys identify cached data and how staleness decides when a refetch happens.
Query keys identify data
TanStack Query stores each result in a cache. The query key is the lookup key for that cache. A key is an array, and two queries with equal keys share one cache entry. Keys are compared by value, not by reference, so ['user', 1] always matches ['user', 1].
Any value the query function depends on belongs in the key. When a value in the key changes, the library treats it as a different query. It reads that entry from the cache or fetches it.
import { useQuery } from '@tanstack/react-query';
async function fetchUsers(status, signal) {
const response = await fetch(`/api/users?status=${status}`, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
function UserList({ status }) {
const { data, isPending } = useQuery({
queryKey: ['users', { status }],
queryFn: ({ signal }) => fetchUsers(status, signal),
});
if (isPending) return <p>Loading...</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}If status changes from 'active' to 'inactive', the key changes and the component reads a separate entry. This replaces the manual race-condition handling from earlier chapters. Each response is stored under its own key, so a late response cannot overwrite data for a different input.
Fresh, stale, and inactive
Each cache entry moves through states:
- Fresh: the data is recent enough. The library returns it without a network request.
- Stale: the data may be out of date. The library still returns it immediately, then may refetch in the background.
- Inactive: no mounted component uses the entry. It stays in the cache for a while, then is removed.
Two options control this, and they are easy to confuse.
| Option | Default | Meaning |
|---|---|---|
| `staleTime` | `0` | Milliseconds after a fetch before data counts as stale. |
| `gcTime` | 5 minutes | Milliseconds an inactive entry stays in the cache before removal. |
Because staleTime defaults to 0, data becomes stale the moment it arrives. The library refetches it when a new component mounts with that key, when the window regains focus, and when the network reconnects.
Tuning staleness
Set staleTime to match how often the data changes. A list of countries rarely changes, so a long staleTime avoids pointless requests.
import { useQuery } from '@tanstack/react-query';
function CountrySelect() {
const { data } = useQuery({
queryKey: ['countries'],
queryFn: async ({ signal }) => {
const response = await fetch('/api/countries', { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
},
staleTime: 60 * 60 * 1000,
});
return (
<select>
{(data ?? []).map((country) => (
<option key={country.code}>{country.name}</option>
))}
</select>
);
}For the next hour, any component that mounts with ['countries'] gets the cached list with no request.
Common errors
- Missing key values. If the query function uses
userIdbut the key omits it, every user shares one cache entry and shows the wrong data. - Confusing the two timers.
staleTimecontrols refetching.gcTimecontrols memory. RaisinggcTimedoes not stop refetches. - Unstable keys. Build keys from plain values such as strings, numbers, and objects. Do not include functions or class instances.
Exercise
A component calls useQuery with queryKey ['user'] and a function that fetches /api/users/${userId}. Two components pass different userId values. What goes wrong, and how do you fix it?
Show answer
Both components read the same cache entry, so one user's data can appear for the other. Add the id to the key: ['user', userId]. Each id then gets its own entry.
Exercise
You set staleTime to 30000 and gcTime to 0 on a query. A component using it unmounts and mounts again 10 seconds later. Is a request sent?
Show answer
The entry is removed right after the last component unmounts, because gcTime is 0. The remount finds no cached data and fetches again, even though the data would have been fresh for 30 seconds.