Query Key Structure
Query keys must be arrays. The simplest form is an array with a single string:Type Definition
Fromtypes.ts:53-61, query keys are defined as:
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:Query Key Serialization
Query keys are serialized to a query hash using thehashQueryKeyByOptions function. This hash is used internally for cache lookups.
From queryCache.ts:113-116:
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:Query Key Matching
Exact Matching
By default, queries match exactly:Prefix Matching
Withoutexact: true, keys match by prefix:
Partial Matching
ThematchQuery function (used internally) supports partial matching:
Query Key in Query Function
The query key is available in the query function context: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 inuseQuery.test.tsx:46-53:
examples/react/basic/src/index.tsx:26-34: