Skip to content
React Query logo

React Query

Officialv5.11.0

@kubb/plugin-react-query

kubb add plugin-react-query

Call operations

Use the generated TanStack Query hooks and factories in React: queries, mutations, infinite lists, and suspense.

What each plugin generates

Each hook and its helpers live in a file named after the hook, such as src/gen/hooks/useGetPetById.ts.

OperationExports
Query (GET, QUERY)getPetByIdQueryKey, getPetByIdQueryOptions, plus useGetPetById with hooks
Mutation (POST, PUT, PATCH, DELETE)updatePetMutationKey, updatePetMutationOptions, plus useUpdatePet with hooks
Infinite, with infinite and hooksfindPetsByTagsInfiniteQueryKey, findPetsByTagsInfiniteQueryOptions, useFindPetsByTagsInfinite
Suspense, with suspense and hooksuseGetPetByIdSuspense, plus useFindPetsByTagsSuspenseInfinite with infinite
Server-Sent Events or JSON LinesNothing. Call the client function directly.

Call a hook

The examples set hooks: true, and integerType: 'number' on the adapter so petId is a number. Path keys keep their spec names unless you set pathParamsCasing.

The first argument takes the request groups: path, query, headers. The second takes TanStack Query options in query, with query.client for the QueryClient, and request config such as baseURL or signal in client.

import { useGetPetById } from './gen/hooks/useGetPetById'

const { data, error, isLoading } = useGetPetById(
  { path: { petId: 1 } },
  { query: { staleTime: 60_000 }, client: { baseURL: 'https://api.example.com/v1' } },
)

Prefetch and invalidate

The factories work without hooks, so you can prefetch or invalidate outside a component:

import { getPetByIdQueryKey, getPetByIdQueryOptions } from './gen/hooks/useGetPetById'
import { queryClient } from './queryClient' // the QueryClient you pass to QueryClientProvider

await queryClient.prefetchQuery(getPetByIdQueryOptions({ path: { petId: 1 } }))
queryClient.invalidateQueries({ queryKey: getPetByIdQueryKey({ path: { petId: 1 } }) })

TanStack Query keys shows the default keys. To change them, set queryKey and mutationKey. To share options across hooks, set customOptions.

Handle errors

Each hook calls the client with throwOnError: true, so a failed request sets TanStack Query's error, typed from the spec's error responses.

Next, set the base URL, auth, and interceptors on your client plugin: plugin-fetch, plugin-axios, plugin-ky, or your own module with plugin-client.