Tanstack Query Integration For React
This guide shows how to integrate oRPC with Tanstack Query for React. For an introduction, please review the Basic Guide first.
Installation
sh
npm install @orpc/react-query@latest @tanstack/react-query@latest
sh
yarn add @orpc/react-query@latest @tanstack/react-query@latest
sh
pnpm add @orpc/react-query@latest @tanstack/react-query@latest
sh
bun add @orpc/react-query@latest @tanstack/react-query@latest
sh
deno install npm:@orpc/react-query@latest npm:@tanstack/react-query@latest
Setup
Before you begin, ensure you have already configured a server-side client or a client-side client.
ts
import { createORPCReactQueryUtils } from '@orpc/react-query'
export const orpc = createORPCReactQueryUtils(client)
orpc.planet.find.queryOptions({ input: { id: 123 } })
//
Avoiding Query/Mutation Key Conflicts
Prevent key conflicts by passing a unique base key when creating your utils:
ts
const userORPC = createORPCReactQueryUtils(userClient, {
path: ['user']
})
const postORPC = createORPCReactQueryUtils(postClient, {
path: ['post']
})
Using React Context
Integrate oRPC React Query utils into your React app with Context:
Create the Context:
tsimport {
createContext,useContext} from 'react' import {RouterUtils} from '@orpc/react-query' import {RouterClient} from '@orpc/server' typeORPCReactUtils=RouterUtils<RouterClient<typeofrouter>> export constORPCContext=createContext<ORPCReactUtils| undefined>(undefined) export functionuseORPC():ORPCReactUtils{ constorpc=useContext(ORPCContext) if (!orpc) { throw newError('ORPCContext is not set up properly') } returnorpc}Provide the Context in Your App:
tsxexport function App() { const [client] = useState<RouterClient<typeof router>>(() => createORPCClient(link)) const [orpc] = useState(() => createORPCReactQueryUtils(client)) return ( <ORPCContext.Provider value={orpc}> <YourApp /> </ORPCContext.Provider> ) }
Use the Utils in Components:
tsconst
orpc=useORPC() constquery=useQuery(orpc.planet.find.queryOptions({input: {id: 123 } }))
skipToken
for Disabling Queries
You can still use skipToken by conditionally overriding the queryFn
property:
ts
import { skipToken, useQuery } from '@tanstack/react-query'
const options = orpc.planet.find.queryOptions({
input: { id: 123 },
})
const query = useQuery({
...options,
queryFn: condition ? skipToken : options.queryFn,
})