Set up the React Query Integration
How to use and setup tRPC in React
On this page
1. Install dependencies
The following dependencies should be installed.
pnpm add @trpc/server @trpc/client @trpc/react-query @tanstack/react-querynpm install @trpc/server @trpc/client @trpc/react-query @tanstack/react-queryyarn add @trpc/server @trpc/client @trpc/react-query @tanstack/react-querybun add @trpc/server @trpc/client @trpc/react-query @tanstack/react-query2. Import your AppRouter
Import your AppRouter type into the client application. This type holds the shape of your entire API.
utils/trpc.ts
import type { AppRouter } from '../server/router';3. Create tRPC hooks
Create a set of strongly-typed React hooks from your AppRouter type signature with createTRPCReact.
utils/trpc.ts
import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/router';
export const trpc = createTRPCReact<AppRouter>();4. Add tRPC providers
Create a tRPC client, and wrap your application in the tRPC Provider, as below. You will also need to set up and connect React Query, which they document in more depth.
App.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';
import React, { useState } from 'react';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}5. Fetch data
You can now use the tRPC React Query integration to call queries and mutations on your API.
pages/IndexPage.tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const userQuery = trpc.getUser.useQuery({ id: 'id_bilbo' });
const userCreator = trpc.createUser.useMutation();
return (
<div>
<p>{userQuery.data?.name}</p>
<button onClick={() => userCreator.mutate({ name: 'Frodo' })}>
Create Frodo
</button>
</div>
);
}