Skip to content
tRPC

Partners

Migrating from the classic React Client

Migrating from the classic React Client

On this page

There are a few approaches to migrate over, and this library is a significant departure from the classic client, so we're not expecting anybody to do it in one shot. But you will probably want to try a combination of...

Codemod migration

Run the upgrade CLI from the folder with your tsconfig.json, on a git working tree without uncommitted changes:

npx @trpc/upgrade --yes

It runs two transforms over the files git tracks:

  • Setup: createTRPCReact becomes createTRPCContext, trpc.Provider becomes TRPCProvider, and trpc.createClient() becomes createTRPCClient(). A createTRPCNext setup becomes the same file exporting makeTRPCClient(), makeQueryClient() and a withTRPC() for _app, which hydrates trpcState like before. See Moving from createTRPCNext.
  • Hooks: each hook becomes the TanStack Query hook with an options factory, such as useQuery(trpc.a.queryOptions(input)), and trpc.useUtils() becomes useQueryClient() with the matching filters and keys. trpc.useQueries(), useSuspenseQueries(), utils.client and getQueryKey() are covered too, as in the table below. Each component or hook that needs it gets const trpc = useTRPC().

Then it installs @trpc/tanstack-react-query, and uninstalls @trpc/react-query and @trpc/next unless a file still imports them, e.g. createServerSideHelpers from @trpc/react-query/server. Pass --skipTanstackQuery to leave your packages alone, or --transforms provider or --transforms hooks to run one transform. Without --yes or --transforms, it asks which to run.

What it can't move safely, such as ssr: true or a trpc used outside a component, gets a TODO(@trpc/upgrade) comment. Afterwards, format the changed files, typecheck, and search for those comments:

npx tsc --noEmit

Gradual migration

The new and classic clients are compatible with each other and can live together in the same application. This means you can start migrating by using the new client in new parts of your application, and gradually migrate over existing usage as you see fit. Most importantly, Query Keys are identical, which means you can use the new client and classic client together and still rely on TanStack Query's caching.

Migrating the provider

Install the new package, and create its hooks next to the classic ones

pnpm add @trpc/tanstack-react-query
npm install @trpc/tanstack-react-query
yarn add @trpc/tanstack-react-query
bun add @trpc/tanstack-react-query
utils/trpc.ts
import { createTRPCReact } from '@trpc/react-query';
import { createTRPCContext } from '@trpc/tanstack-react-query';
import type { AppRouter } from '../server/router';

// Classic, until nothing uses it
export const trpc = createTRPCReact<AppRouter>();

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

The classic trpc.Provider takes the tRPC client as client; TRPCProvider takes it as trpcClient. While both are mounted, give them the same QueryClient and tRPC client, so they share one cache. trpc.createClient() becomes createTRPCClient<AppRouter>() from @trpc/client.

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

export function App(props: { children: React.ReactNode }) {
  const [queryClient] = useState(() => new QueryClient());
  const [trpcClient] = useState(() =>
    createTRPCClient<AppRouter>({
      links: [httpBatchLink({ url: '/api/trpc' })],
    }),
  );

  return (
    <QueryClientProvider client={queryClient}>
      <TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
        {/* Remove once nothing uses the classic hooks */}
        <trpc.Provider client={trpcClient} queryClient={queryClient}>
          {props.children}
        </trpc.Provider>
      </TRPCProvider>
    </QueryClientProvider>
  );
}

Migrating Queries

A classic query would look like this

import { trpc } from './trpc';

function Users() {
  const greetingQuery = trpc.greeting.useQuery({ name: 'Jerry' });

  // greetingQuery.data === 'Hello Jerry'
}

and changes to

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

function Users() {
  const trpc = useTRPC();

  const greetingQuery = useQuery(trpc.greeting.queryOptions({ name: 'Jerry' }));

  // greetingQuery.data === 'Hello Jerry'
}

Migrating Invalidations and other QueryClient usages

A classic invalidation pattern would look like this

import { trpc } from './trpc';

function Users() {
  const utils = trpc.useUtils();

  async function invalidateGreeting() {
    await utils.greeting.invalidate({ name: 'Jerry' });
  }
}

and changes to

import { useQueryClient } from '@tanstack/react-query';
import { useTRPC } from './trpc';

function Users() {
  const trpc = useTRPC();
  const queryClient = useQueryClient();

  async function invalidateGreeting() {
    await queryClient.invalidateQueries(
      trpc.greeting.queryFilter({ name: 'Jerry' }),
    );
  }
}

This is the same for any QueryClient usage, instead of using tRPC's useUtils you can now follow the TanStack documentation directly

Migrating Mutations

A classic mutation might look like this

import { trpc } from './trpc';

function Users() {
  const createUserMutation = trpc.createUser.useMutation();

  createUserMutation.mutate({ name: 'Jerry' });
}

and changes to

import { useMutation } from '@tanstack/react-query';
import { useTRPC } from './trpc';

function Users() {
  const trpc = useTRPC();

  const createUserMutation = useMutation(trpc.createUser.mutationOptions());

  createUserMutation.mutate({ name: 'Jerry' });
}

Equivalents for the other hooks and useUtils

Every hook takes the trpc from useTRPC(), and utils becomes const queryClient = useQueryClient(). Here a is a procedure and r a router.

ClassicNew
trpc.a.useSuspenseQuery(input)useSuspenseQuery(trpc.a.queryOptions(input)), which returns the query, not a [data, query] pair
trpc.a.useInfiniteQuery(input, opts)useInfiniteQuery(trpc.a.infiniteQueryOptions(input, opts))
trpc.a.useSubscription(input, opts)useSubscription(trpc.a.subscriptionOptions(input, opts)), imported from @trpc/tanstack-react-query
trpc.useQueries((t) => [t.a(input)])useQueries({ queries: [trpc.a.queryOptions(input)] })
utils.a.invalidate(input)queryClient.invalidateQueries(trpc.a.queryFilter(input))
utils.r.invalidate() / utils.invalidate()queryClient.invalidateQueries(trpc.r.pathFilter()) / (trpc.pathFilter())
utils.a.refetch(), reset(), cancel()refetchQueries, resetQueries, cancelQueries with the same filters
utils.a.fetch(input), prefetch, ensureDataqueryClient.fetchQuery(trpc.a.queryOptions(input)), prefetchQuery, ensureQueryData
utils.a.fetchInfinite(input), prefetchInfinitefetchInfiniteQuery(trpc.a.infiniteQueryOptions(input)), prefetchInfiniteQuery
utils.a.getData(input), setData(input, updater)queryClient.getQueryData(trpc.a.queryKey(input)), setQueryData(trpc.a.queryKey(input), updater)
utils.a.getInfiniteData, setInfiniteDataThe same, with trpc.a.infiniteQueryKey(input)
utils.clientuseTRPCClient()

Migrating abortOnUnmount

The classic integration takes abortOnUnmount when you create the client, which sets the default for every query — an individual query can still override it through its own trpc option

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

export const trpc = createTRPCReact<AppRouter>({
  abortOnUnmount: true,
});

createTRPCContext() takes no options, so there is no global equivalent. Set abortOnUnmount per query instead, in the same trpc option the classic integration uses per request

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

function Users() {
  const trpc = useTRPC();

  const greetingQuery = useQuery(
    trpc.greeting.queryOptions({ name: 'Jerry' }, { trpc: { abortOnUnmount: true } }),
  );
}

Migrating overrides

createTRPCContext() doesn't take the classic overrides either. To run something after every mutation, such as invalidating the whole cache, use TanStack's own MutationCache callbacks

utils/query-client.ts
import { MutationCache, QueryClient } from '@tanstack/react-query';

export const queryClient: QueryClient = new QueryClient({
  mutationCache: new MutationCache({
    onSuccess: () => queryClient.invalidateQueries(),
  }),
});

Common mistakes

  • Destructuring useSuspenseQuery. The classic hook returns [data, query]; TanStack's returns the query, so const [data] = ... becomes const { data } = ....
  • Mounting a second QueryClient. While both clients are in use, a separate QueryClient for each provider splits the cache, so an invalidation from one side doesn't refresh queries on the other. Share one.
  • Losing @trpc/react-query mid-migration. The upgrade CLI uninstalls it unless you pass --skipTanstackQuery.
  • Trusting the codemod blindly. It rewrites the common patterns only. Typecheck after it runs, and check custom wrappers around tRPC hooks by hand.