Sub topic 5
Designing query keys
This chapter assumes you can use useQuery and useMutation and know why the cache has staleTime and gcTime. It builds on the earlier chapters on useQuery and query status.
What a query key does
A query key identifies a piece of server data in the cache. TanStack Query uses it for four jobs:
- Cache lookup. Two components that use the same key share one cache entry and one request.
- Refetch triggers. When the key changes, the query reads a different cache entry and fetches it if needed.
- Targeting.
invalidateQueries,setQueryData,cancelQueriesandgetQueryDataall find entries by key. - Devtools labels. The key is how you recognize an entry when you inspect the cache.
In v5 a key must be an array at the top level. Its items can be strings, numbers, objects, or nested arrays, as long as they can be serialized to JSON.
How keys are compared
The library hashes a key by serializing it to JSON, and it sorts object properties first. Two keys are the same entry when their hashes match. This has consequences you can check yourself:
| Key A | Key B | Same entry? |
|---|---|---|
| `['todos', 1]` | `['todos', 1]` | Yes |
| `['todos', 1]` | `['todos', '1']` | No, a number and a string serialize differently |
| `['todos', { status: 'done', page: 1 }]` | `['todos', { page: 1, status: 'done' }]` | Yes, object property order is ignored |
| `['todos', 'done', 1]` | `['todos', 1, 'done']` | No, array order matters |
| `['todos', { status: undefined }]` | `['todos', {}]` | Yes, `undefined` properties are dropped when serializing |
Two practical rules follow. Keep id types consistent, because a route parameter is a string and your API client may expect a number. Put values in the same position every time.
The dependency rule
Treat the key like the dependency array of useEffect. Every variable that the query function reads must appear in the key. If it doesn't, two different requests share one cache entry, and the screen shows data for the wrong parameters.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodosByStatus(status: 'done' | 'open'): Promise<Todo[]> {
const res = await fetch(`/api/todos?status=${status}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
// Bug: `status` is used in queryFn but missing from the key.
// Every status shares the cache entry ['todos'].
export function useTodosBroken(status: 'done' | 'open') {
return useQuery({
queryKey: ['todos'],
queryFn: () => fetchTodosByStatus(status),
})
}
// Fix: the key describes everything the request depends on.
export function useTodosFixed(status: 'done' | 'open') {
return useQuery({
queryKey: ['todos', { status }],
queryFn: () => fetchTodosByStatus(status),
})
}With the broken version, switching status does not trigger a fetch, because the key did not change. The component keeps showing the first result. The package @tanstack/eslint-plugin-query includes an exhaustive-deps rule that reports this mistake.
Order keys from general to specific
Matching in invalidateQueries and similar methods works by prefix. A filter key matches every entry whose key starts with the same items. So order the items from the broad scope to the narrow one:
- The resource name, such as
'todos'. - The kind of query, such as
'list'or'detail'. - The parameters, such as a filters object or an id.
Invalidating ['todos'] marks every node in the tree stale. Invalidating ['todos', 'list'] marks only the list entries and leaves the detail entries alone. Matching is a prefix match by default. Pass exact: true to match one entry only.
Objects inside the key are matched partially. A filter of ['todos', 'list', { status: 'done' }] matches any list entry whose filters object contains status: 'done', whatever other properties it has.
Centralize keys in a factory
Typing key arrays by hand in every component invites typos. A key factory is a plain object of functions that build keys in one place. Each level is built from the level above it, so the hierarchy cannot drift.
// todoKeys.ts
export type TodoFilters = { status?: 'done' | 'open'; page?: number }
export const todoKeys = {
all: ['todos'] as const,
lists: () => [...todoKeys.all, 'list'] as const,
list: (filters: TodoFilters) => [...todoKeys.lists(), filters] as const,
details: () => [...todoKeys.all, 'detail'] as const,
detail: (id: number) => [...todoKeys.details(), id] as const,
}The as const assertions give TypeScript precise tuple types, so setQueryData and getQueryData can infer types from the key's shape in some cases and catch wrong shapes in others.
Use the factory in hooks and in mutations:
// useTodos.ts
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { todoKeys, type TodoFilters } from './todoKeys'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodos(filters: TodoFilters): Promise<Todo[]> {
const params = new URLSearchParams()
if (filters.status) params.set('status', filters.status)
if (filters.page) params.set('page', String(filters.page))
const res = await fetch(`/api/todos?${params}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function useTodos(filters: TodoFilters) {
return useQuery({
queryKey: todoKeys.list(filters),
queryFn: () => fetchTodos(filters),
})
}
export function useRenameTodo() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (todo: { id: number; title: string }) => {
const res = await fetch(`/api/todos/${todo.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: todo.title }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
},
onSuccess: (_data, todo) => {
// Refresh every list, and only the one affected detail entry.
queryClient.invalidateQueries({ queryKey: todoKeys.lists() })
queryClient.invalidateQueries({ queryKey: todoKeys.detail(todo.id) })
},
})
}Renaming one todo refetches the lists on screen and one detail entry. It does not touch the detail entries of other todos.
Common mistakes
- Missing variables. The query function reads a value that the key does not contain. The cache serves stale data for the wrong parameters.
- Mixed id types.
['todos', 'detail', 1]and['todos', 'detail', '1']are separate entries. Invalidating one leaves the other stale. Convert route parameters to numbers once, near the router. - Unstable key contents. Do not put values that change on every render in the key, such as
Date.now()or a freshly generated id. Each render then creates a new cache entry and a new request. - Non-serializable values. Functions, class instances, and
MaporSetobjects do not serialize usefully. Two different instances can hash identically, or one value can hash differently from run to run. - Overly wide keys. A key with a large object, such as a full form state, creates many cache entries for values that the request never uses. Include only what changes the response.
- Positional filters. Writing
['todos', status, page]makes it hard to omit a filter later without shifting positions. An object is easier to extend.
Reading the key inside the query function
The query function receives a context object that includes the key. You can read parameters from it, which keeps the key and the request in sync.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
export function useTodo(id: number) {
return useQuery({
queryKey: ['todos', 'detail', id] as const,
queryFn: async ({ queryKey }): Promise<Todo> => {
const [, , todoId] = queryKey
const res = await fetch(`/api/todos/${todoId}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
},
})
}This style is optional. Closing over id, as in the earlier chapters, works equally well. Reading from queryKey helps when the query function lives in a separate file and you want the key to be its only input.
Exercise
A screen shows a todo list filtered by status and page. The hook uses queryKey: ['todos', status] and queryFn: () => fetchTodos({ status, page }). Users report that clicking "next page" seems to do nothing. Explain why, and write the corrected key using an object so the filters can grow later.
Show answer
page is used by the query function but not by the key, so every page maps to the same cache entry. Changing page does not change the key, so no new fetch starts and the screen keeps the first page's data. The fix is queryKey: ['todos', 'list', { status, page }]. Now each combination of status and page has its own entry, and invalidating ['todos', 'list'] still refreshes all of them.