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 builds its key in a query factory, together with the query function:
41β
42```ts
43export const projectsQueries = {
44 all: () => ['projects'] as const,
45 list: (page: number, delayMs: number, forceError: boolean) =>
46 queryOptions({
47 queryKey: [
48 ...projectsQueries.all(),
49 'list',
50 page,
51 delayMs,
52 forceError,
53 ] as const,
54 queryFn: () => projectsAPI.getProjects(page, delayMs, forceError),
55 }),
56}
57```
58β
59## Deterministic Hashing
60β
61Object key order does not matter inside a query key:
62β
63```ts
64const keyA = ['todos', { status, page }]
65const keyB = ['todos', { page, status }]
66```
67β
68Array item order does matter:
69β
70```ts
71const keyA = ['todos', status, page]
72const keyB = ['todos', page, status]
73```
74β
75## Query Keys as Dependencies
76β
77If your query function reads a reactive host property, include that value in the query key:
78β
79```ts
80class UserTodos extends LitElement {
81 static properties = {
82 userId: { type: String },
83 }
84β
85 userId = ''
86β
87 private readonly todos = createQueryController(this, () => ({
88 queryKey: ['todos', this.userId],
89 queryFn: () => fetchTodos(this.userId),
90 }))
91}
92```
93β
94This lets Lit Query cache each user's todos separately and refetch when the host state changes.