Sub topic 5
Designing query keys
This chapter assumes you can fetch data with useQuery and know that a query function returns a Promise. It covers how to build query keys that identify data correctly.
What a query key does
A query key is an array that identifies one cache entry. TanStack Query hashes the key into a string and uses that string to look up cached data. Two useQuery calls with equal keys share one cache entry and one request. Keys that differ get separate entries.
The hash is based on JSON serialization, so the key must contain only values that serialize cleanly: strings, numbers, booleans, arrays, and plain objects.
The key must describe the inputs
Treat the key like a dependency array. Every value the query function reads should appear in the key. When one of those values changes, the key changes, and the query loads that data on its own. Without the value in the key, the cache cannot tell the two requests apart.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
type Filters = { status: 'all' | 'done' | 'open'; page: number }
async function fetchTodos(filters: Filters): Promise<Todo[]> {
const params = new URLSearchParams({
status: filters.status,
page: String(filters.page),
})
const res = await fetch(`/api/todos?${params}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function FilteredTodos({ filters }: { filters: Filters }) {
const { data } = useQuery({
queryKey: ['todos', 'list', filters],
queryFn: () => fetchTodos(filters),
})
return <p>{data?.length ?? 0} todos</p>
}Here filters sits inside the key. Switching from page 1 to page 2 creates a new entry. Going back to page 1 finds the old entry in the cache.
Matching rules
- Array order matters.
['todos', 1]and[1, 'todos']are different keys. - Object key order does not matter.
{ status: 'done', page: 1 }and{ page: 1, status: 'done' }hash the same. - Types matter.
['todos', 1]and['todos', '1']are different keys. A route parameter is a string, so convert it to a number if the rest of your code uses numbers. - Matching functions such as
invalidateQueriesuse prefix matching. A partial key matches every key that starts with it.
| Filter passed in | Matches `['todos', 'list', { page: 1 }]` | Matches `['todos', 5]` | Matches `['users']` |
|---|---|---|---|
| `['todos']` | Yes | Yes | No |
| `['todos', 'list']` | Yes | No | No |
| `['users']` | No | No | Yes |
Order keys from general to specific
Put the broad category first and the narrow details last: entity, then kind of query, then parameters. For example, use ['todos', 'list', filters] for lists and ['todos', 'detail', id] for single items. With this layout, invalidateQueries({ queryKey: ['todos'] }) refreshes everything about todos. A narrower filter refreshes only the lists.
If the same keys appear in many files, put them in one helper object so a typo cannot create a silent cache miss.
export const todoKeys = {
all: ['todos'] as const,
lists: () => [...todoKeys.all, 'list'] as const,
list: (filters: { status: string; page: number }) =>
[...todoKeys.lists(), filters] as const,
detail: (id: number) => [...todoKeys.all, 'detail', id] as const,
}Common errors
- Missing variable. The query function uses
userId, but the key does not. Users see another user's cached data. - Unstable values. Putting a new object that holds functions, class instances, or a changing timestamp in the key creates a new entry on every render.
- Mismatched types. Using
'1'in one component and1in another splits the cache in two.
Exercise
A component calls useQuery with queryKey: ['projects'] and a query function that fetches /api/projects?owner=${ownerId}. Users report that switching owners shows the previous owner's projects. What is wrong, and what is the fix?
Show answer
ownerId is used by the query function but is missing from the key, so every owner maps to the same cache entry. Add it to the key, for example queryKey: ['projects', ownerId], so each owner gets a separate entry.