Skip to main content
Query keys are the foundation of TanStack Query’s caching system. They uniquely identify queries and are used to manage cache data, invalidation, and refetching.

Query Key Structure

Query keys must be arrays. The simplest form is an array with a single string:
Query keys can include multiple elements for hierarchical organization:

Type Definition

From types.ts:53-61, query keys are defined as:
This means query keys are always arrays and can contain any serializable values.
TanStack Query v4+ requires query keys to be arrays. If you’re migrating from v3, change string keys like 'posts' to ['posts'].

Query Key Best Practices

1. Hierarchical Structure

Organize keys from generic to specific:

2. Include All Dependencies

Include all variables that the query function depends on:

3. Consistent Ordering

Maintain consistent ordering of key elements:
Object keys in query keys are not automatically sorted. Use a consistent order or the queries will be treated as different.

Query Key Serialization

Query keys are serialized to a query hash using the hashQueryKeyByOptions function. This hash is used internally for cache lookups. From queryCache.ts:113-116:
The hash function serializes the key deterministically:

Array-Based Keys

Simple Values

Arrays can contain strings, numbers, booleans, etc.:

Objects in Keys

Objects are useful for complex filters:

Nested Objects

Nested structures are supported:

Query Key Factories

Create factory functions for consistent key generation:
Use as const assertions to ensure type safety and prevent accidental mutations of query keys.

Query Key Matching

Exact Matching

By default, queries match exactly:

Prefix Matching

Without exact: true, keys match by prefix:

Partial Matching

The matchQuery function (used internally) supports partial matching:

Query Key in Query Function

The query key is available in the query function context:
From the source, the context includes the queryKey at query.ts:450-461:

Custom Query Hash Function

You can provide a custom hash function:

Effective Key Organization

By Resource

By Feature

Type Safety with Query Keys

Use TypeScript to ensure type safety:

Query Key Examples from Source

From the test suite in useQuery.test.tsx:46-53:
And from the basic example in examples/react/basic/src/index.tsx:26-34: