Your Query Key Is an API: Organizing TanStack Query Caches
Make TanStack Query cache keys predictable with a small key factory. Separate list and detail data, include filters, and invalidate deliberately after mutations.
A React application can use TanStack Query and still show the wrong list after a filter changes. The request URL is correct, the server returns the right data, and the cache key quietly describes several different requests as one.

A query key is the identity of a cached result. Treat its shape as part of your application’s data API. The examples below use the TanStack Query v5 object syntax and assume your app already has a QueryClientProvider.
The Problem: One Key, Several Results
// Missing the data-shaping variables in the key.
useQuery({
queryKey: ['projects'],
queryFn: () => fetchProjects(tenantId, status),
});The query function depends on tenantId and status. If the key omits them, it cannot independently identify those datasets. Include the variables that change the returned data, including pagination or search parameters when applicable.
Step 1: Introduce a Small Key Factory
type Filters = { status: 'open' | 'closed'; page: number };
export const projectKeys = {
lists: (tenantId: string) =>
['projects', tenantId, 'list'] as const,
list: (tenantId: string, filters: Filters) =>
['projects', tenantId, 'list', filters] as const,
detail: (tenantId: string, id: string) =>
['projects', tenantId, 'detail', id] as const,
};This hierarchy is an application design choice: a tenant’s lists share one prefix, while each detail record has an exact key. A regular list and an infinite query should have different namespaces because their cached data structures differ.
Step 2: Keep the Request and Key Aligned
type Project = { id: string; name: string };
async function fetchProjects(tenantId: string, filters: Filters) {
const params = new URLSearchParams({
status: filters.status,
page: String(filters.page),
});
const response = await fetch(
'/api/tenants/' + encodeURIComponent(tenantId) + '/projects?' + params
);
if (!response.ok) throw new Error('Unable to load projects');
return response.json() as Promise<Project[]>;
}
const filters: Filters = { status, page };
const query = useQuery({
queryKey: projectKeys.list(tenantId, filters),
queryFn: () => fetchProjects(tenantId, filters),
});The endpoint and its Project response are illustrative application contracts. The type assertion does not validate the JSON at runtime. Validate at the network boundary when the response cannot be trusted to match that shape.
Step 3: Invalidate What the Mutation Changes
const mutation = useMutation({
// updateProject is your API client; it must reject failed requests.
mutationFn: updateProject,
onSuccess: async (project: Project) => {
queryClient.setQueryData(
projectKeys.detail(tenantId, project.id), project
);
await queryClient.invalidateQueries({
queryKey: projectKeys.lists(tenantId),
});
},
});Use setQueryData only when the mutation returns the complete detail representation that key expects. A partial response is not a safe replacement for a larger object. Lists may need refetching because the changed record can move between filters or alter sort order.
Prefix invalidation marks matching queries stale and, by default, refetches active matches in the background. It does not mean every inactive list immediately makes a network request. Await the invalidation promise when the mutation flow should wait for those refetches.
Where the Key Factory Stops
Tenant-scoped keys prevent accidental cache identity collisions; they do not authorize API access. Enforce permissions on the server and clear or appropriately isolate private cached data when the signed-in identity changes. Never place access tokens in query keys.
Keep the factory boring. A few named functions are usually sufficient. Introduce a larger abstraction only when repeated mistakes reveal a concrete rule that the abstraction can enforce.