Catalog My learning Blog
tRPC Course: Type-Safe APIs with TypeScript and React · Phase 3 · Lesson 9 · 5 min read

tRPC with React and TanStack Query

On this page
  1. Why pair tRPC with TanStack Query
  2. Set up the provider
  3. Fetch data with queryOptions
  4. Change data with mutationOptions
  5. Understand query keys
  6. Check yourself

Why pair tRPC with TanStack Query

The tRPC client from Day 2 fetches data, but a React app needs more: loading and error states, caching so the same data isn't fetched twice, refetching when the window regains focus, and a way to refresh lists after a change. TanStack Query (formerly React Query) does all of that. tRPC's job is to give it typed options for each procedure.

tRPC has two React integrations. The older @trpc/react-query wraps the hooks for you (trpc.task.list.useQuery()). The newer @trpc/tanstack-react-query, which this course uses, gives you *options* that you pass to TanStack Query's own hooks. The tRPC team recommends the newer one for new projects, since your code uses the standard TanStack Query API and its docs apply directly.

Shell
npm i @trpc/client @trpc/tanstack-react-query @tanstack/react-query

Set up the provider

Create the typed context once, in its own file:

TypeScript
// src/utils/trpc.ts
import { createTRPCContext } from '@trpc/tanstack-react-query';
import type { AppRouter } from '../../server/routers/_app';

export const { TRPCProvider, useTRPC } = createTRPCContext<AppRouter>();

Then wrap the app. Both clients are created inside useState, so they're made once per app and not on every render:

TypeScript
// src/App.tsx
import { useState } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import superjson from 'superjson';
import { TRPCProvider } from './utils/trpc';
import type { AppRouter } from '../server/routers/_app';

export function App() {
  const [queryClient] = useState(() => new QueryClient());
  const [trpcClient] = useState(() =>
    createTRPCClient<AppRouter>({
      links: [httpBatchLink({ url: '/trpc', transformer: superjson })],
    }),
  );
  return (
    <QueryClientProvider client={queryClient}>
      <TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
        <Tasks />
      </TRPCProvider>
    </QueryClientProvider>
  );
}

Fetch data with queryOptions

useTRPC() returns an object shaped like your router. Each query procedure has a queryOptions(input) method that produces everything useQuery needs: a query key, a fetch function and the types.

TypeScript
import { useQuery } from '@tanstack/react-query';
import { useTRPC } from './utils/trpc';

function Tasks() {
  const trpc = useTRPC();
  const tasks = useQuery(trpc.task.list.queryOptions({}));

  if (tasks.isPending) return <p>Loading…</p>;
  if (tasks.isError) return <p role="alert">{tasks.error.message}</p>;

  return (
    <ul>
      {tasks.data.items.map((t) => (
        <li key={t.id}>{t.done ? '[x]' : '[ ]'} {t.title} ({t.createdAt.getFullYear()})</li>
      ))}
    </ul>
  );
}

tasks.data is fully typed from the server, and because superjson is configured, createdAt really is a Date, so getFullYear() works.

You can add any TanStack Query option as a second argument: trpc.task.list.queryOptions({}, { staleTime: 30_000 }).

Two more patterns come up often. To skip a query until you have its input, pass skipToken:

JavaScript
import { skipToken } from '@tanstack/react-query';

const task = useQuery(trpc.task.byId.queryOptions(selectedId ? { id: selectedId } : skipToken));

And because these are plain options, they work with every TanStack Query API, like useSuspenseQuery(trpc.me.queryOptions()) or queryClient.prefetchQuery(trpc.task.byId.queryOptions({ id })) when the user hovers over a link.

Change data with mutationOptions

Mutations work the same way, with mutationOptions:

JavaScript
import { useMutation, useQueryClient } from '@tanstack/react-query';

function NewTask() {
  const trpc = useTRPC();
  const queryClient = useQueryClient();
  const [title, setTitle] = useState('');

  const create = useMutation(trpc.task.create.mutationOptions({
    onSuccess: () => queryClient.invalidateQueries({ queryKey: trpc.task.list.queryKey() }),
  }));

  return (
    <form onSubmit={(e) => { e.preventDefault(); create.mutate({ title }); setTitle(''); }}>
      <input aria-label="title" value={title} onChange={(e) => setTitle(e.target.value)} />
      <button disabled={create.isPending}>Add</button>
      {create.error?.data?.fieldErrors?.title && <p role="alert">{create.error.data.fieldErrors.title[0]}</p>}
    </form>
  );
}

create.error is a typed TRPCClientError, so the fieldErrors from Day 5's formatter are available with autocompletion.

Understand query keys

Invalidation works by matching query keys. tRPC builds them from the procedure path and input, and you can see them by logging the options:

Code
trpc.task.list.queryOptions({ done: false }).queryKey
  [["task","list"],{"input":{"done":false},"type":"query"}]
trpc.task.list.queryKey()        [["task","list"]]     (every list query, any input)
trpc.task.pathKey()              [["task"]]            (everything under task)
trpc.task.create.mutationOptions().mutationKey
  [["task","create"]]

TanStack Query matches keys by prefix, so a shorter key covers more queries:

Code
// refetch one exact list
queryClient.invalidateQueries({ queryKey: trpc.task.list.queryKey({ done: false }) });
// refetch every task.list query, whatever its input
queryClient.invalidateQueries({ queryKey: trpc.task.list.queryKey() });
// refetch everything in the task router
queryClient.invalidateQueries(trpc.task.pathFilter());

Start broad. Invalidating all task queries after a mutation is cheap and always correct. Narrow it only when you measure a real cost.

You can also read and write the cache directly, with full types: queryClient.getQueryData(trpc.task.list.queryKey({})) returns the list's data type or undefined. You'll use that tomorrow for optimistic updates.

TipDon't create the tRPC client or the QueryClient in module scope if you render on the server. Each request needs its own QueryClient, or users could see each other's cached data. Creating them in useState, as above, is safe for client-only apps.

Check yourself

A typed options object with a query key and fetch function. You pass it to TanStack Query hooks like useQuery, useSuspenseQuery or prefetchQuery.

Invalidate trpc.task.list.queryKey() with no input. TanStack Query matches query keys by prefix, so the shorter key covers every task.list query, whatever filters or page sizes it used. For everything under the task router, use trpc.task.pathFilter().

Pass skipToken instead of the input, for example queryOptions(id ? { id } : skipToken). The query stays idle until id exists, and the types stay correct, because the input is never a half-filled object. It's clearer than the older enabled: false pattern.

On the server, module-level objects are shared between every request, so one user's cached data could be served to another user. Create a new QueryClient per request on the server. In a client-only app, creating it once inside useState is fine.

For Zod validation failures, the message is a JSON list of issues, not friendly text. Read create.error.data?.fieldErrors instead, which the error formatter adds, and show each field's first message next to its input. The error is fully typed, so the field names autocomplete.