Parameterize list queries
A list endpoint supports filters or pagination.
TanStack · Pipe
queryKey is the array identity for TanStack Query data. It determines cache identity, carries request parameters, and is passed to queryFn through QueryFunctionContext.
A queryKey is an array that names and parameterizes cached query data. TanStack Query hashes it into a stable identity, uses it to distinguish cache entries, and supplies it to the query function so request variables can be derived consistently.
useQuery({ queryKey: ['todos', { status, page }], queryFn: fetchTodoList })| Name | Type | Description |
|---|---|---|
queryKey | unknown[] | The array used to identify and parameterize the query. |
The page documents queryKey as an option rather than a standalone return value.
const todosQuery = useQuery({
queryKey: ['todos', { status, page }],
queryFn: fetchTodoList,
})
async function fetchTodoList({ queryKey }) {
const [, { status, page }] = queryKey
const response = await fetch(`/api/todos?status=${status}&page=${page}`)
if (!response.ok) throw new Error('Request failed')
return response.json()
}The key identifies the requested todo list and is available to the query function through its context.
A list endpoint supports filters or pagination.
A detail endpoint needs an entity identifier.
Several components need the same cached request.
A queryKey is the identity for a query's cached data. TanStack Query hashes it into a stable hash and uses key changes to update the query.
Follow-up: How can a query function use request parameters? It receives a QueryFunctionContext containing queryKey, so it can destructure variables from the key.
Include values that distinguish the requested data, such as an item ID or filter and page object. The query function can then read those values from its context instead of closing over them.
Follow-up: What benefit does this provide for extracted functions? The same function can derive its request entirely from the supplied context.
The key is passed to the query function as part of QueryFunctionContext. This lets an extracted function read the current key and build the corresponding request.
Follow-up: What else is in the context? The documentation lists the QueryClient, an AbortSignal, and optional metadata alongside queryKey.
Query KeysQueryFunctionContextqueryFnuseQuery