Skip to content

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 add 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 {  } 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:

  1. Create the Context:

    ts
    import { ,  } 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 
    }
  2. Provide the Context in Your App:

    tsx
    export function App() {
      const [client] = useState<RouterClient<typeof router>>(() => createORPCClient(link))
      const [orpc] = useState(() => createORPCReactQueryUtils(client))
    
      return (
        <ORPCContext.Provider value={orpc}>
          <YourApp />
        </ORPCContext.Provider>
      )
    }
  3. Use the Utils in Components:

    ts
    const  = ()
    
    const  = (...({ : { : 123 } }))

Released under the MIT License.