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 can be as simple as a 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## String-Only Query Keys
9β
10The simplest form of a key is actually not an array, but an individual string. When a string query key is passed, it is converted to an array internally with the string as the only item in the query key. This format is useful for:
11β
12- Generic List/Index resources
13- Non-hierarchical resources
14β
15```js
16// A list of todos
17useQuery('todos', ...) // queryKey === ['todos']
18β
19// Something else, whatever!
20useQuery('somethingSpecial', ...) // queryKey === ['somethingSpecial']
21```
22β
23## Array Keys
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```js
33// An individual todo
34useQuery(['todo', 5], ...)
35// queryKey === ['todo', 5]
36β
37// And individual todo in a "preview" format
38useQuery(['todo', 5, { preview: true }], ...)
39// queryKey === ['todo', 5, { preview: true }]
40β
41// A list of todos that are "done"
42useQuery(['todos', { type: 'done' }], ...)
43// queryKey === ['todos', { type: 'done' }]
44```
45β
46## Query Keys are hashed deterministically!
47β
48This means that no matter the order of keys in objects, all of the following queries are considered equal:
49β
50```js
51useQuery(['todos', { status, page }], ...)
52useQuery(['todos', { page, status }], ...)
53useQuery(['todos', { page, status, other: undefined }], ...)
54```
55β
56The following query keys, however, are not equal. Array item order matters!
57β
58```js
59useQuery(['todos', status, page], ...)
60useQuery(['todos', page, status], ...)
61useQuery(['todos', undefined, page, status], ...)
62```
63β
64## If your query function depends on a variable, include it in your query key
65β
66Since query keys uniquely describe the data they are fetching, they should include any variables you use in your query function that **change**. For example:
67β
68```js
69function Todos({ todoId }) {
70 const result = useQuery(['todos', todoId], () => fetchTodoById(todoId))
71}
72```
73β
74## Further reading
75β
76For tips on organizing Query Keys in larger applications, have a look at [Effective React Query Keys](../community/tkdodos-blog#8-effective-react-query-keys) from
77the Community Resources.