Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query-keys.md

74 lines2.5 KB

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))
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.