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

query-options.md

52 lines1.6 KB

1---
2id: query-options
3title: Query Options
4---
5​
6One of the best ways to share `queryKey` and `queryFn` between multiple places, yet keep them co-located to one another, is to use the `queryOptions` helper. At runtime, this helper just returns whatever you pass into it, but it has a lot of advantages when using it [with TypeScript](../typescript.md#typing-query-options). You can define all possible options for a query in one place, and you'll also get type inference and type safety for all of them.
7​
8[//]: # 'Example1'
9​
10```ts
11import { queryOptions } from '@tanstack/react-query'
12​
13function groupOptions(id: number) {
14 return queryOptions({
15 queryKey: ['groups', id],
16 queryFn: () => fetchGroups(id),
17 staleTime: 5 * 1000,
18 })
20​
21// usage:
22​
23useQuery(groupOptions(1))
24useSuspenseQuery(groupOptions(5))
25useQueries({
26 queries: [groupOptions(1), groupOptions(2)],
27})
28queryClient.query(groupOptions(23))
29queryClient.setQueryData(groupOptions(42).queryKey, newGroups)
30```
31​
32[//]: # 'Example1'
33​
34For Infinite Queries, a separate [`infiniteQueryOptions`](../reference/functions/infiniteQueryOptions.md) helper is available.
35​
36[//]: # 'SelectDescription'
37​
38You can still override some options at the component level. A very common and useful pattern is to create per-component [`select`](./render-optimizations.md#select) functions:
39​
40[//]: # 'SelectDescription'
41[//]: # 'Example2'
42​
43```ts
44// Type inference still works, so query.data will be the return type of select instead of queryFn
45​
46const query = useQuery({
47 ...groupOptions(1),
48 select: (data) => data.groupName,
49})
50```
51​
52[//]: # 'Example2'