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

query-keys.md

94 lines2.1 KB

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 }),
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 }))
92```
93​
94This lets Lit Query cache each user's todos separately and refetch when the host state changes.