Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Queries and Keys

Query Keys

Understand how query keys identify cached data: arrays, variables inside keys, deterministic hashing, hierarchical keys, key factories and common mistakes.

A query key is the name of a piece of server data. TanStack Query uses it to store the data, to share it between components, to refetch it and to invalidate it. If you remember one rule about keys, make it this one: everything your query function depends on must be in the key. This lesson shows what keys look like, how they are compared, and how to organize them so a large app stays manageable.

Keys are arrays

In v5 a key is always an array at the top level. The elements can be strings, numbers, booleans, plain objects and nested arrays; anything that can be serialized to JSON.

JavaScript
useQuery({ queryKey: ["todos"], queryFn: fetchTodos });
useQuery({ queryKey: ["todo", 5], queryFn: () => fetchTodo(5) });
useQuery({ queryKey: ["todos", { status: "done", page: 2 }], queryFn: () => fetchTodos("done", 2) });

The first element is usually a string naming the resource. The rest describe which version of the resource you want: an id, filters, a page number.

Variables belong in the key

Think of the key as the dependency array of useEffect. When a variable that the function uses changes, the key must change, so Query treats it as a different query: it looks up (or creates) a different cache entry and fetches it.

The key follows the variable

Each user has its own cache entry. Going back to user 1 shows the stored result at once, and because staleTime is a minute, no new request is made. If you had forgotten id in the key, every user would share the entry ["user"] and you would see the wrong name.

How keys are compared

Query hashes the key with a deterministic JSON serialization. Two consequences:

  • Object property order does not matter. ["todos", { a: 1, b: 2 }] and ["todos", { b: 2, a: 1 }] are the same key.
  • Array order does matter. ["todos", 1] and [1, "todos"] are different keys.
JavaScript
// These are the same entry:
["todos", { status: "done", page: 1 }]
["todos", { page: 1, status: "done" }]

// These are different entries:
["todos", "done"]
["todos", { status: "done" }]

Because comparison is structural, you can put a freshly created object in the key on every render; it will not trigger a refetch as long as the contents are equal. What breaks equality is a value JSON cannot represent in a stable way: functions, class instances with private state, Map, Set and undefined values (a property with undefined is dropped, so { a: undefined } equals {}).

Put plain data in keys, not objects such as a Date. A Date serializes to a string, which is stable, but a new Date() each render has a different value every millisecond and creates a new query every time. Use an ISO date string or a rounded timestamp instead.

Hierarchical keys and partial matching

The real power of arrays shows up with invalidation and other cache operations. Methods such as invalidateQueries match by prefix: a filter key matches every query whose key starts with it.

JavaScript
queryClient.invalidateQueries({ queryKey: ["todos"] });
// matches ["todos"], ["todos", "done"], ["todos", { page: 2 }], ["todos", 5, "comments"]

So design keys from general to specific: resource, then scope or id, then details.

TEXT
["todos"]                          every todo query
["todos", "list"]                  all lists
["todos", "list", { status }]      one filtered list
["todos", "detail", 5]             one todo

Pass exact: true when you only want the single entry with that exact key.

Query key factories

When keys are written inline in many components, a typo or a different shape silently creates a different cache entry. Large codebases centralize keys in a small object, often called a key factory:

A key factory and prefix matching

After clicking the button, the two list lines get a new counter value and the other two stay unchanged. staleTime: Infinity makes sure nothing else refetches, so the only fetches you see are the ones caused by invalidation.

The factory gives you autocomplete, a single place to change a key's shape and safe prefix helpers (todoKeys.lists()).

Keys and the query function context

Instead of repeating variables, the query function receives the key itself, so it cannot drift out of sync:

JavaScript
useQuery({
  queryKey: ["todo", id],
  queryFn: ({ queryKey }) => {
    const [, todoId] = queryKey;
    return fetchTodo(todoId);
  },
});

For small cases the closure () => fetchTodo(id) is simpler and fully typed in TypeScript. Both are fine; the rule that the key must list every variable stays the same. The next lesson, Query Functions, covers the context object in detail.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A query function uses a userId variable. Where should the variable appear?

    The key is the cache identity. If userId is missing from it, different users share one cache entry.
  2. 2. Are ['todos', { a: 1, b: 2 }] and ['todos', { b: 2, a: 1 }] the same key?

    Keys are hashed deterministically, so objects with the same properties and values match regardless of order.
  3. 3. invalidateQueries({ queryKey: ['todos'] }) refetches which entries?

    Filters match by prefix unless exact: true is passed.
  4. 4. What is the main benefit of a query key factory?

    A factory avoids typos and inconsistent shapes that would silently create separate cache entries.

Summary

  • A key is an array that names the data; include every variable the query function uses.
  • Hashing is structural: object order is ignored, array order is not.
  • Design keys from general to specific so prefix matching can target groups.
  • Use a key factory in bigger apps to keep keys consistent.
  • Avoid unstable values such as functions or changing Date objects in keys.

Next: Query Functions