www/blog/2025-02-17-new-tanstack-react-query-integration.mdx
We are excited to announce the new TanStack React Query integration for tRPC is now available on tRPC's next-release. Compared to our classic React Query Integration it's simpler and more TanStack Query-native, choosing to utilize the QueryOptions and MutationOptions interfaces native to TanStack React Query, instead of wrapping useQuery and useMutation with our own client.
// @jsx: react-jsx
// @filename: server.ts
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
export const appRouter = t.router({
greeting: t.procedure.input(z.object({ name: z.string() })).query(({ input }) => `Hello ${input.name}`),
});
export type AppRouter = typeof appRouter;
// @filename: trpc.ts
import { createTRPCContext } from '@trpc/tanstack-react-query';
import type { AppRouter } from './server';
export const { TRPCProvider, useTRPC } = createTRPCContext<AppRouter>();
// @filename: greeting.tsx
// ---cut---
import { useQuery } from '@tanstack/react-query';
import { useTRPC } from './trpc';
export function Greeting() {
const trpc = useTRPC();
const greetingQuery = useQuery(trpc.greeting.queryOptions({ name: 'Jerry' }));
// greetingQuery.data === 'Hello Jerry'
return null;
}
With this new client we're removing a layer of abstraction which is a common source of confusion for new users, and instead providing a more direct way to work with TanStack React Query which will feel immediately familiar to those who are following TanStack's own documentation. It also means we need less tRPC documentation to explain it, though we of course have documentation to get you started.
You can read our original RFC behind this change here which goes into some detail. But some of our key reasons are:
It's not going anywhere soon! We're committing to maintaining it for a long time to come, but it won't receive any significant new features and we'll consider it stable.
We still recommend new projects start with the new TanStack React Query integration, and existing projects to consider migrating over gradually.
While the classic client is going to be maintained for a long time to come, we recommend new projects start with the new client and active projects consider gradually migrating over.
Both clients are compatible with each other and can exist in the same application, so you can migrate at your own pace. We are also working on a codemod which we would love community contributions to. We'd like to thank @reaper for his contributions to the codemod so far!