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 --yesIt runs two transforms over the files git tracks:
- Setup:
createTRPCReactbecomescreateTRPCContext,trpc.ProviderbecomesTRPCProvider, andtrpc.createClient()becomescreateTRPCClient(). AcreateTRPCNextsetup becomes the same file exportingmakeTRPCClient(),makeQueryClient()and awithTRPC()for_app, which hydratestrpcStatelike before. See Moving fromcreateTRPCNext. - Hooks: each hook becomes the TanStack Query hook with an options factory, such as
useQuery(trpc.a.queryOptions(input)), andtrpc.useUtils()becomesuseQueryClient()with the matching filters and keys.trpc.useQueries(),useSuspenseQueries(),utils.clientandgetQueryKey()are covered too, as in the table below. Each component or hook that needs it getsconst 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 --noEmitGradual 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-querynpm install @trpc/tanstack-react-queryyarn add @trpc/tanstack-react-querybun add @trpc/tanstack-react-queryimport { 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.
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.
| Classic | New |
|---|---|
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, ensureData | queryClient.fetchQuery(trpc.a.queryOptions(input)), prefetchQuery, ensureQueryData |
utils.a.fetchInfinite(input), prefetchInfinite | fetchInfiniteQuery(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, setInfiniteData | The same, with trpc.a.infiniteQueryKey(input) |
utils.client | useTRPCClient() |
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
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
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, soconst [data] = ...becomesconst { data } = .... - Mounting a second
QueryClient. While both clients are in use, a separateQueryClientfor each provider splits the cache, so an invalidation from one side doesn't refresh queries on the other. Share one. - Losing
@trpc/react-querymid-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.