0
Fork 0
mirror of https://github.com/TanStack/query.git synced 2026-11-16 22:50:20 +00:00
query/docs/framework/react/guides/query-options.md
Wonsuk Choi 4c568a28c8
docs(react-query): generate reference docs with TypeDoc (#11366)
* docs(vue-query,solid-query): inline react reference content instead of 'ref'-ing hand-written react docs

* docs(react-query): generate reference docs with TypeDoc

* docs(vue-query,solid-query): fix dangling suspense-hook links left over from the react content copy

* docs(solid-query): apply solid's callback call form to inlined reference examples

* docs(react-query): correct inaccurate JSDoc statements flagged in review

* docs(vue-query,solid-query): fix reactivity-aware examples and inaccurate type signatures flagged in review

* docs(vue-query,solid-query): fix remaining type/behavior inaccuracies flagged in second review

* docs(react-query): stop implying a default queryFn defers a fetch the way 'enabled: false' does

* docs(vue-query): mark 'mutate'/'mutateAsync' per-call options as optional
2026-09-02 16:06:54 +09:00

1.6 KiB

id title
query-options Query Options

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.

import { queryOptions } from '@tanstack/react-query'

function groupOptions(id: number) {
  return queryOptions({
    queryKey: ['groups', id],
    queryFn: () => fetchGroups(id),
    staleTime: 5 * 1000,
  })
}

// usage:

useQuery(groupOptions(1))
useSuspenseQuery(groupOptions(5))
useQueries({
  queries: [groupOptions(1), groupOptions(2)],
})
queryClient.query(groupOptions(23))
queryClient.setQueryData(groupOptions(42).queryKey, newGroups)

For Infinite Queries, a separate infiniteQueryOptions helper is available.

You can still override some options at the component level. A very common and useful pattern is to create per-component select functions:

// Type inference still works, so query.data will be the return type of select instead of queryFn

const query = useQuery({
  ...groupOptions(1),
  select: (data) => data.groupName,
})