Open History to see the last commit
1---
2id: query-keys
3title: Query Keys
4---
5β
6At its core, React Query manages query caching for you based on query keys. Query keys have to be an Array at the top level, and can be as simple as an Array with a single string, or as complex as an array of many strings and nested objects. As long as the query key is serializable, and **unique to the query's data**, you can use it!
7β
8## Simple Query Keys
9β
10The simplest form of a key is an array with constants values. This format is useful for:
11β
12- Generic List/Index resources
13- Non-hierarchical resources
14β
15```tsx
16// A list of todos
17useQuery(['todos'], ...)
18β
19// Something else, whatever!
20useQuery(['something', 'special'], ...)
21```
22β
23## Array Keys with variables
24β
25When a query needs more information to uniquely describe its data, you can use an array with a string and any number of serializable objects to describe it. This is useful for:
26β
27- Hierarchical or nested resources
28 - It's common to pass an ID, index, or other primitive to uniquely identify the item
29- Queries with additional parameters
30 - It's common to pass an object of additional options
31β
32```tsx
33// An individual todo
34useQuery(['todo', 5], ...)
35β
36// An individual todo in a "preview" format
37useQuery(['todo', 5, { preview: true }], ...)
38β
39// A list of todos that are "done"
40useQuery(['todos', { type: 'done' }], ...)
41```
42β
43## Query Keys are hashed deterministically!
44β
45This means that no matter the order of keys in objects, all of the following queries are considered equal:
46β
47```tsx
48useQuery(['todos', { status, page }], ...)
49useQuery(['todos', { page, status }], ...)
50useQuery(['todos', { page, status, other: undefined }], ...)
51```
52β
53The following query keys, however, are not equal. Array item order matters!
54β
55```tsx
56useQuery(['todos', status, page], ...)
57useQuery(['todos', page, status], ...)
58useQuery(['todos', undefined, page, status], ...)
59```
60β
61## If your query function depends on a variable, include it in your query key
62β
63Since query keys uniquely describe the data they are fetching, they should include any variables you use in your query function that **change**. For example:
64β
65```tsx
66function Todos({ todoId }) {
67 const result = useQuery(['todos', todoId], () => fetchTodoById(todoId))
68}
69```
70β
71## Further reading
72β
73For tips on organizing Query Keys in larger applications, have a look at [Effective React Query Keys](../community/tkdodos-blog#8-effective-react-query-keys) and check the [Query Key Factory Package](../community/lukemorales-query-key-factory) from
74the Community Resources.