How to Use tRPC with React Query for Seamless Type-Safe APIs
Combining tRPC with React Query gives you a fully typed, end-to-end API layer without any code generation. React Query handles caching and state management, while tRPC ensures your client and server types stay perfectly in sync. This tutorial walks through the essentials.
First, install the required packages: @trpc/client, @trpc/server, @trpc/react-query, @tanstack/react-query. Then create a tRPC client using createTRPCReact and wrap your app in a QueryClientProvider and .Provider.
1. Setting Up the Provider
In your root component, initialize a QueryClient and a tRPC client instance. Use createTRPCReact to generate hooks. Then render both providers:
const trpc = createTRPCReact<AppRouter>();
function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({ links: [httpBatchLink({ url: '/api/trpc' })] })
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<YourApp />
</QueryClientProvider>
</trpc.Provider>
);
}
2. Defining Queries and Mutations
Use trpc.hello.useQuery() to fetch data and trpc.user.create.useMutation() to write data. React Query handles caching, retries, and stale management automatically. Example:
function UserList() {
const { data, isLoading } = trpc.user.list.useQuery();
const mutation = trpc.user.create.useMutation({
onSuccess: () => queryClient.invalidateQueries(['user.list']),
});
// ... render
}
3. Key Benefits
- No schema duplication – types flow from server to client automatically.
- Full autocompletion – your IDE knows every procedure and input.
- React Query features – caching, refetching, optimistic updates work out of the box.
By pairing tRPC with React Query, you eliminate boilerplate and runtime errors. Just define your API in one place and let TypeScript and React Query handle the rest.