Course contentsShow
← React
Lesson 1813 of 2,39642. Data Fetching LibrariesFree lesson

Setting Up tRPC with TanStack Query

Installing @trpc/client, @trpc/server, and @trpc/react-query; configuring the tRPC client with a TanStack Query adapter.

Setting Up tRPC with TanStack Query

You'll learn how to install tRPC packages and wire them together with TanStack Query for type-safe data fetching.

Now that you understand what tRPC offers—end-to-end type safety between your frontend and backend—it's time to actually set it up. tRPC works beautifully with TanStack Query, letting you keep all the caching, refetching, and mutation patterns you've learned while gaining full TypeScript inference.

Installing the Packages

You need three core packages:

npm install @trpc/client @trpc/server @trpc/react-query
  • @trpc/server: Defines your API procedures on the backend
  • @trpc/client: The client-side runtime for making requests
  • @trpc/react-query: The React adapter that bridges tRPC with TanStack Query

Configuring the tRPC Client

The key piece is creating a tRPC client configured with TanStack Query's adapter:

import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from './server/router'; // Your backend router types

// Create typed hooks
export const trpc = createTRPCReact<AppRouter>();

Then wrap your app with both the TanStack Query and tRPC providers:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';

const queryClient = new QueryClient();
const trpcClient = trpc.createClient({
  links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
});

function App() {
  return (
    <trpc.Provider client={trpcClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>
        {/* Your app */}
      </QueryClientProvider>
    </trpc.Provider>
  );
}

The httpBatchLink automatically batches multiple requests into one network call, and the AppRouter type inference gives you autocomplete and type safety everywhere.

Key Takeaway: Setting up tRPC requires three packages and two providers—the tRPC client wraps your QueryClient, giving you type-safe hooks that still use all of TanStack Query's caching and refetching behavior under the hood.