One 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. 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.
1import { queryOptions } from '@tanstack/react-query'
2
3function groupOptions(id: number) {
4 return queryOptions({
5 queryKey: ['groups', id],
6 queryFn: () => fetchGroups(id),
7 staleTime: 5 * 1000,
8 })
9}
10
11// usage:
12
13useQuery(groupOptions(1))
14useSuspenseQuery(groupOptions(5))
15useQueries({
16 queries: [groupOptions(1), groupOptions(2)],
17})
18queryClient.prefetchQuery(groupOptions(23))
19queryClient.setQueryData(groupOptions(42).queryKey, newGroups)
For Infinite Queries, a separate infiniteQueryOptions
helper is available.