Skip to content
React Query logo

React Query

Officialv5.11.0

@kubb/plugin-react-query

kubb add plugin-react-query

Options

Pass these options to pluginReactQuery(). Shared options link to Shared plugin options.

Options overview

OptionPurposeDefault
clientClient plugin the hooks call.Auto-detected
returnTypeWhat the hooks resolve to.'data'
hooksEmit use* hooks on top of the factories.false
queryWhich methods become queries, and the TanStack import.{ methods: ['GET', 'QUERY'], importPath: '@tanstack/react-query' }
query.methodsMethods that become queries.['GET', 'QUERY']
query.importPathImport path of the query helpers.'@tanstack/react-query'
queryKeyBuild the queryKey of each query.queryKeyTransformer
mutationWhich methods become mutations, and the TanStack import.{ methods: ['POST', 'PUT', 'PATCH', 'DELETE'], importPath: '@tanstack/react-query' }
mutation.methodsMethods that become mutations.['POST', 'PUT', 'PATCH', 'DELETE']
mutation.importPathImport path of the mutation helpers.'@tanstack/react-query'
mutationKeyBuild the mutationKey of each mutation.mutationKeyTransformer
infiniteGenerate infinite queries for pagination.false
infinite.queryParamQuery parameter for the page cursor.'id'
infinite.initialPageParamFirst pageParam.0
infinite.nextParamPath to the next cursor.null
infinite.previousParamPath to the previous cursor.null
infinite.getNextPageParamCompute the next page param.null
infinite.getPreviousPageParamCompute the previous page param.null
infinite.cursorParamDeprecated cursor field.null
suspenseGenerate useSuspenseQuery hooks.false
customOptionsRoute every hook through your own options function.None
customOptions.importPathModule of your function.None, required
customOptions.nameName of your function.'useCustomHookOptions'
outputWhere files are written.{ path: 'hooks', barrel: { type: 'named' } }
groupSplit output by tag or path.None
includeKeep only operations that match.None
excludeSkip operations that match.[]
overrideApply different options per pattern.[]
resolverCustomize generated names and file paths.resolverReactQuery
macrosRewrite AST nodes before printing.[]

Option details

client

The client plugin the hooks call. Kubb detects a lone client plugin, so set client only when several are registered. Generation fails when none is.

Type'fetch' | 'axios' | 'ky' | 'client'
Requiredfalse
'fetch'
'axios'
'ky'
'client'
Calls @kubb/plugin-client. Your client module must also export RequestConfig and ResponseErrorConfig.

returnType

What the hooks resolve to.

Type'data' | 'full'
Requiredfalse
Default'data'
'data'
Resolves to the success body.
'full'
Resolves to the client's whole RequestResult, so a hook can read the status and headers. Needs a client plugin with returnType'full' or 'plain', or generation fails.
pluginReactQuery({ returnType: 'full' })

// with integerType: 'number' on the adapter
const { data: result } = useGetPetById({ path: { petId: 1 } })
const etag = result?.response.headers.get('ETag')

hooks

Set true to generate useQuery and useMutation hooks on top of the queryOptions, mutationOptions, and key helpers. Call operations lists every export.

Typeboolean
Requiredfalse
Defaultfalse

query

Which operations become queries and where TanStack Query is imported from. false skips query output.

TypePartial<Query> | false
Requiredfalse
Default{ methods: ['GET', 'QUERY'], importPath: '@tanstack/react-query' }

query.methods

HTTP methods treated as queries. A method in neither list gets no helper, so keep 'QUERY' when you replace it.

TypeArray<string>
Requiredfalse
Default['GET', 'QUERY']

query.importPath

Module for queryOptions, useQuery, and their variants, such as a wrapper that sets a default QueryClient.

Typestring
Requiredfalse
Default'@tanstack/react-query'

queryKey

Builds each query's queryKey from the operation node and the variant: 'query', 'suspenseQuery', 'infiniteQuery', or 'suspenseInfiniteQuery'. The default key is [{ url, params }, query, body].

Type(props: { node, casing, variant }) => Array<unknown>
Requiredfalse
DefaultqueryKeyTransformer
Returned strings are copied into the generated code as written, so wrap a string literal in JSON.stringify(...).

To extend the default, spread it. See TanStack Query keys.

import { queryKeyTransformer } from '@kubb/plugin-react-query'

queryKey: (props) => [JSON.stringify('v2'), ...queryKeyTransformer(props)]

mutation

Which operations become mutations and where TanStack Query is imported from. false skips mutation output.

TypePartial<Mutation> | false
Requiredfalse
Default{ methods: ['POST', 'PUT', 'PATCH', 'DELETE'], importPath: '@tanstack/react-query' }

mutation.methods

HTTP methods treated as mutations. A method also in query.methods stays a query.

TypeArray<string>
Requiredfalse
Default['POST', 'PUT', 'PATCH', 'DELETE']

mutation.importPath

Module for mutationOptions and useMutation.

Typestring
Requiredfalse
Default'@tanstack/react-query'

mutationKey

Builds each mutation's mutationKey, for batched invalidations or useMutationState. It works like queryKey with variant: 'mutation'. The default key is [{ url }].

Type(props: { node, casing, variant }) => Array<unknown>
Requiredfalse
DefaultmutationKeyTransformer
import { mutationKeyTransformer } from '@kubb/plugin-react-query'

mutationKey: (props) => [JSON.stringify('v2'), ...mutationKeyTransformer(props)]

infinite

Adds infiniteQueryOptions and useInfiniteQuery to each query operation that takes the infinite.queryParam parameter. Needs hooks: true.

TypePartial<Infinite> | false
Requiredfalse
Defaultfalse
Set nextParam or getNextPageParam. Otherwise hasNextPage never turns false for a non-array response. See Infinite queries.

infinite.queryParam

Query parameter that carries the page cursor.

Typestring
Requiredfalse
Default'id'

infinite.initialPageParam

pageParam of the first fetch. Give it the type of the query parameter.

Typeunknown
Requiredfalse
Default0

infinite.nextParam

Path to the next cursor on the response, in dot notation ('pagination.next.id') or array form (['pagination', 'next', 'id']).

Typestring | Array<string> | null
Requiredfalse
Defaultnull

infinite.previousParam

Path to the previous cursor, in the same forms as nextParam.

Typestring | Array<string> | null
Requiredfalse
Defaultnull

infinite.getNextPageParam

Source of TanStack Query's getNextPageParam, for a next page you must compute. Pass a string, a function, or definePageParam, which types the page and the page parameter.

Typestring | PageParamFn | null
Requiredfalse
Defaultnull
Only the function's source is copied, so it cannot use variables from the config file.
kubb.config.ts
import { definePageParam, pluginReactQuery } from '@kubb/plugin-react-query'

type PetsPage = { hasNext: boolean; number: number }

pluginReactQuery({
  hooks: true,
  infinite: {
    queryParam: 'page',
    getNextPageParam: definePageParam<PetsPage, number>((lastPage) => (lastPage.hasNext ? lastPage.number + 1 : undefined)),
  },
})

infinite.getPreviousPageParam

Source of TanStack Query's getPreviousPageParam, in the same forms as getNextPageParam.

Typestring | PageParamFn | null
Requiredfalse
Defaultnull

infinite.cursorParam

Deprecated. Use nextParam and previousParam. A top-level response field, not a dot path, that holds the cursor for both directions.

Typestring | null
Requiredfalse
Defaultnull

suspense

Pass {} to add useSuspenseQuery hooks, plus useSuspenseInfiniteQuery when infinite is set. Needs hooks: true.

Typeobject | false
Requiredfalse
Defaultfalse

customOptions

Calls one function of yours from every hook to share options such as staleTime. Kubb also writes a HookOptions type, keyed by hook name. Needs hooks: true.

Type{ importPath: string; name?: string }
Requiredfalse

Each hook calls it with { hookName, operationId }, and per-call options win over its result:

src/gen/hooks/useCustomHookOptions.ts
import type { HookOptions } from './HookOptions'

export function useCustomHookOptions({ hookName }: { hookName: keyof HookOptions; operationId: string }) {
  if (hookName === 'useGetPetById') {
    return { staleTime: 60_000 } satisfies HookOptions['useGetPetById']
  }
  return {}
}

customOptions.importPath

Module of the function, resolved from the generated hooks folder. If the path is inside the plugin's output folder and the file is missing, Kubb writes a starter file.

Typestring
Requiredtrue when customOptions is set

customOptions.name

Exported name of the function.

Typestring
Requiredfalse
Default'useCustomHookOptions'

resolver

Overrides generated names. Members you leave out keep resolverReactQuery. See resolver for the shared members.

TypeResolverPatch<ResolverReactQuery>
Requiredfalse
Partial override
type ResolverReactQueryPatch = {
  // plus the shared name, file, and imports members
  query?: {
    name?(node: OperationNode): string // 'useGetPetById'
    optionsName?(node: OperationNode): string // 'getPetByIdQueryOptions'
    keyName?(node: OperationNode): string // 'getPetByIdQueryKey'
    keyTypeName?(node: OperationNode): string // 'GetPetByIdQueryKey'
  }
  // same members, with a Suspense, Infinite, or SuspenseInfinite suffix
  suspenseQuery?: ResolverReactQueryPatch['query']
  infiniteQuery?: ResolverReactQueryPatch['query']
  suspenseInfiniteQuery?: ResolverReactQueryPatch['query']
  mutation?: {
    name?(node: OperationNode): string // 'useUpdatePet'
    optionsName?(node: OperationNode): string // 'updatePetMutationOptions'
    keyName?(node: OperationNode): string // 'updatePetMutationKey'
  }
  hook?: {
    optionsName?(): string // 'HookOptions'
    customOptionsName?(): string // 'getCustomHookOptions'
  }
}