Skip to main content
Query keys are the foundation of TanStack Query’s caching system. They uniquely identify queries and determine when data should be refetched.

What are Query Keys?

Query keys are arrays that uniquely identify a query. They can be as simple as a single string or as complex as nested objects:
Query keys must be arrays in TanStack Query v4+. Single strings are no longer supported.

Query Key Structure

Query keys are serialized deterministically, so these are equivalent:
Query keys are hashed in a deterministic way, but object property order doesn’t matter. However, arrays are order-sensitive.

Query Key Conventions

1

Use Arrays

Always use arrays for query keys, even for simple queries.
2

Hierarchy

Structure keys from general to specific.
3

Include Dependencies

Include all variables that the query function depends on.
4

Consistent Naming

Use consistent naming patterns across your application.

Query Key Factories

Create factories to ensure consistent query keys:
Query key factories make it easy to manage and invalidate related queries.

Partial Matching

Query keys support partial matching for invalidation:

Exact Matching

Use exact matching when you need precision:

Query Key Dependencies

Always include query function dependencies in the key:
If you don’t include all dependencies in the query key, you may see stale data when those dependencies change.

Dynamic Query Keys

Query keys can include computed values:

Query Key Hashing

TanStack Query hashes query keys internally:

Custom Query Key Hash Function

Customize how query keys are hashed:

Accessing Query Data by Key

Retrieve cached data using query keys:

Query Key Best Practices

TypeScript and Query Keys

Type-safe query keys with TypeScript:

Invalidating with Filters

Use filters for fine-grained invalidation control:

Query Key Prefetching

Prefetch data using query keys:

Query Key Patterns

Common patterns for organizing query keys: