Open History to see the last commit
1---
2id: query-keys
3title: Query Keys
4---
5β
6TanStack Query manages caching by query key. Query keys must be arrays at the top level, and they should uniquely describe the data returned by the query function.
7β
8## Simple Keys
9β
10Use simple keys for list resources or non-hierarchical data:
11β
12```ts
13createQueryController(this, {
14 queryKey: ['todos'],
15 queryFn: fetchTodos,
16})
17β
18createQueryController(this, {
19 queryKey: ['settings'],
20 queryFn: fetchSettings,
21})
22```
23β
24## Keys with Variables
25β
26Include variables when they change what the query fetches:
27β
28```ts
29createQueryController(this, () => ({
30 queryKey: ['todo', this.todoId],
31 queryFn: () => fetchTodo(this.todoId),
32}))
33β
34createQueryController(this, () => ({
35 queryKey: ['projects', { page: this.page, filter: this.filter }],
36 queryFn: () => fetchProjects({ page: this.page, filter: this.filter }),
37}))
38```
39β
40The pagination example uses a key shaped like this:
41β
42```ts
43type ProjectsQueryKey = readonly ['projects', number, number, boolean]
44β
45function projectsQueryKey(
46 page: number,
47 delayMs: number,
48 forceError: boolean,
49): ProjectsQueryKey {
50 return ['projects', page, delayMs, forceError] as const
51}
52```
53β
54## Deterministic Hashing
55β
56Object key order does not matter inside a query key:
57β
58```ts
59const keyA = ['todos', { status, page }]
60const keyB = ['todos', { page, status }]
61```
62β
63Array item order does matter:
64β
65```ts
66const keyA = ['todos', status, page]
67const keyB = ['todos', page, status]
68```
69β
70## Query Keys as Dependencies
71β
72If your query function reads a reactive host property, include that value in the query key:
73β
74```ts
75class UserTodos extends LitElement {
76 userId = ''
77β
78 private readonly todos = createQueryController(this, () => ({
79 queryKey: ['todos', this.userId],
80 queryFn: () => fetchTodos(this.userId),
81 }))
82}
83```
84β
85This lets Lit Query cache each user's todos separately and refetch when the host state changes.