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@latestsh
yarn add @orpc/react-query@latest @tanstack/react-query@latestsh
pnpm add @orpc/react-query@latest @tanstack/react-query@latestsh
bun add @orpc/react-query@latest @tanstack/react-query@latestsh
deno add npm:@orpc/react-query@latest npm:@tanstack/react-query@latestSetup
Before you begin, ensure you have already configured a server-side client or a client-side client.
ts
import { } from '@orpc/react-query'
export const = ()
...({ : { : 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 { , } from 'react' import { } from '@orpc/react-query' import { } from '@orpc/server' type = <<typeof >> export const = < | undefined>() export function (): { const = () if (!) { throw new ('ORPCContext is not set up properly') } return }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 = () const = (...({ : { : 123 } }))
