Course contentsShow
← React
Lesson 1771 of 2,39642. Data Fetching LibrariesFree lesson

Query Keys: The Cache Identifier

How query keys work as unique identifiers, array structure, and why they matter for caching.

Query Keys: The Cache Identifier

You'll learn how query keys uniquely identify each cached query and why their structure matters for efficient data management.

What Is a Query Key?

In TanStack Query, every piece of cached data needs a unique identifier — that's the query key. Think of it like a filing system: if you want to store or retrieve a document, you need a label on the folder. Query keys are those labels, telling TanStack Query "this data belongs here."

Query keys are always arrays. Even a simple query uses an array:

useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos
})

Why Arrays?

The array structure lets you build hierarchical identifiers. You can add parameters that make the key more specific:

// Different keys = different cache entries
useQuery({
  queryKey: ['todos'],
  queryFn: fetchAllTodos
})

useQuery({
  queryKey: ['todos', 'completed'],
  queryFn: fetchCompletedTodos
})

useQuery({
  queryKey: ['todos', { userId: 5 }],
  queryFn: () => fetchUserTodos(5)
})

Each of these creates a separate cache entry. They're as distinct as different files in your filing cabinet.

Why This Matters

Query keys determine:

  • Cache lookups: TanStack Query matches keys to find cached data
  • Invalidation: You can invalidate ['todos'] to clear all todo-related queries
  • Refetching: Keys decide which queries update when data changes

Change a single element in the key array, and you get a completely different cache slot. This is powerful: add a filter parameter to the key, and TanStack Query automatically treats it as a new query with its own cache.

Key Takeaway: Query keys are array-based unique identifiers that determine cache storage, retrieval, and invalidation — making them the foundation of TanStack Query's caching system.