Query keys are unique identifiers that React Query uses for caching, invalidation, and refetching. They must be arrays and are compared deeply.
Basic structure:
// Simple key
queryKey: ['posts']
// Key with parameters
queryKey: ['posts', userId]
// Key with complex parameters
queryKey: ['posts', { userId, status: 'published' }]
Key principles:
- Uniqueness: Different keys create separate cache entries
- Hierarchy: Keys are hierarchical, allowing group operations
- Deep comparison: React Query compares keys deeply to determine if data should be refetched
Examples:
// These are different queries with separate cache
queryKey: ['posts'] // All posts
queryKey: ['posts', 1] // Posts for user 1
queryKey: ['posts', 2] // Posts for user 2
// Invalidation example
queryClient.invalidateQueries({ queryKey: ['posts'] }); // Invalidates all post queries
queryClient.invalidateQueries({ queryKey: ['posts', 1] }); // Only user 1's posts
Query keys enable React Query's intelligent caching and make it easy to manage related data.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
The model's verdict: “”
The interactive diagram is below the answer - jump to diagram ↓
This answer is explained by a shared concept diagram - open →