Open History to see the last commit
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 })
19}
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'