Prefetching with handles
On this page
Handles help you avoid request waterfalls. When a component reads the route's params or search params and starts its own query, that query can only start once the component has rendered. A child it renders only after that query loads starts its own query later still. With handles, the loader reads the URL once, starts every query whose input comes from it up front, and passes each component a typed handle as a prop. A query that needs another query's result still waits for it: see Dependent queries.
A handle is a small, serializable reference to a query: its key and input, but no data. You load it in a route loader, a server component or an event handler. The component reads the query from it, fully typed, without naming the procedure or repeating its input.
Handles also fix a gap in the usual prefetch pattern. There, the server prefetches trpc.post.byId.queryOptions({ id }), and the client component repeats the same procedure and input:
- If the inputs differ, the read misses the prefetched data and silently fetches again.
- The client can read a different procedure from the one the server prefetched.
- Nothing shows that a prefetch happened at all.
With handles, the client reads exactly what the server started.
Take a post page at /posts/$id. Its loader, or server component, reads id from the URL, lists the queries the page needs and loads them in one call:
import {
ensureEntry,
loadHandles,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
const [handles] = await loadHandles(trpc, {
// 1. The post: the load waits for it
post: ensureEntry(trpc.post.byId, { id }),
// 2. Its comments: start at the same time, and stream in later
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});The loader returns handles, or a server component passes them on as props. The page reads them without naming a procedure or repeating an input:
import { useSuspenseQuery } from '@tanstack/react-query';
import { fromHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { Suspense } from 'react';
import { Comments } from '~/components/comments';
import { MoreByAuthor } from '~/components/more-by-author';
import { useTRPC } from '~/trpc/client';
export function PostPage(props: {
post: inferQueryHandle<TRPC['post']['byId']>;
comments: inferInfiniteQueryHandle<TRPC['post']['comments']>;
}) {
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, props.post));
return (
<article>
<h1>{postQuery.data.title}</h1>
<Suspense fallback={<p>Loading comments…</p>}>
<Comments comments={props.comments} />
</Suspense>
{/* 3. More by the author: needs the post's authorId */}
<Suspense fallback={<p>Loading more by this author…</p>}>
<MoreByAuthor authorId={postQuery.data.authorId} />
</Suspense>
</article>
);
}More by the author needs the post's authorId, so the loader can't start it from the URL. MoreByAuthor reads it with trpc.post.byAuthor.infiniteQueryOptions({ authorId }), as it would without handles, and its request starts once the post has loaded. Dependent queries shows how to start it with the others.
Mutations don't change: use useTRPC()'s mutationOptions. To show a new comment, refresh the comments handle when the mutation succeeds:
import { useMutation, useQueryClient } from '@tanstack/react-query';
import type { inferInfiniteQueryHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { useTRPC, type TRPC } from '~/trpc/client';
export function AddComment(props: {
comments: inferInfiniteQueryHandle<TRPC['post']['comments']>;
}) {
const trpc = useTRPC();
const queryClient = useQueryClient();
const addComment = useMutation(
trpc.post.addComment.mutationOptions({
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: props.comments.queryKey,
exact: true,
}),
}),
);
return (
<button
onClick={() =>
addComment.mutate({ postId: props.comments.input.postId, text: 'Nice!' })
}
>
Add a comment
</button>
);
}{ queryKey: props.comments.queryKey, exact: true } refreshes exactly the query the handle names. For the other filters, see Invalidation.
The data lives in the cache, not the handle: see Handles carry no data. The cache fills through TanStack Query's dehydrate and hydrate, as in the Server Components guide or TanStack Start's SSR query integration. In a server loader, return dehydrate(queryClient) with the handles, as in React Router.
The components that read handles are the same everywhere: with or without server components, and whatever loaded the handle.
Loading handles
A loader lists its queries as entries, and loadHandles(trpc, entries) starts them all at once, then returns a handle for each:
import {
ensureEntry,
loadHandles,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
const [handles, data] = await loadHandles(trpc, {
// Waits for the post, unless the cache has it
post: ensureEntry(trpc.post.byId, { id }),
// Doesn't wait
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
handles.post;data.post;// The comments may have no data yet, so they aren't on `data`
data.comments;- Building an entry starts nothing. The load starts every entry before it waits for any, so the order of the entries doesn't matter, and you can't make one wait for another by accident.
- It resolves to
[handles, data]: a handle for every entry, by its key, and the data of the entries it waited for. Returnhandlesfrom the loader, or pass them to components as props. - Reading a prefetch entry's
datais a type error, not a silentundefined. Components read it from the handle. - It rejects as soon as an entry it waits for fails, with an error that names the entry. Handle it where you load, for example to show a not-found page: see Errors.
Each entry chooses whether the page waits for its query:
- Don't wait with
prefetchEntry. The page renders at once, and the data streams in later. - Wait with
ensureEntry. The page renders once the data is ready.
fetchEntry is a stricter form of waiting, for code that needs fresh data. See Waiting for fresh data.
Without waiting: prefetchEntry
const [handles] = await loadHandles(trpc, {
post: prefetchEntry(trpc.post.byId, { id }),
});-
The load doesn't wait for it. Unless the cache has fresh data, the request runs in the background.
-
The component that reads the handle can render before the data arrives. If the cache has data, it shows that. If not,
useSuspenseQuerysuspends: wrap it in<Suspense>to show a fallback in its place.useQueryrenders withstatus: 'pending', which with server rendering can cause a hydration mismatch: see Reading withuseQuery.<Suspense fallback={<p>Loading post…</p>}> <Post post={handles.post} /> </Suspense>Without a boundary of your own, React shows the fallback of the nearest boundary above it, which may cover the whole page.
-
It never makes the load reject. If the request fails, the component that reads the handle gets the error: see Errors with prefetch entries.
-
Its data isn't in
data: the query may not have any yet. Readingdata.postis a type error.
Use it for data the page can show a placeholder for: slow queries, content below the fold, secondary panels.
Waiting: ensureEntry
const [handles, data] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
});- The load waits until the cache has data for the query, so the data is ready before anything renders. If the cache had no data and the request fails, the load rejects.
- If the cache already has data, even stale, the load resolves at once with it. Stale data is refetched in the background, and a failed refetch doesn't make the load reject.
data.posthas the data. See Using the data in a loader.- The component that reads the handle finds the data in the cache and renders it at once, with
useSuspenseQueryoruseQuery. It still needs a loading state for when the cache loses the data: see When the cache loses the data.
Use it for data the page can't render without, or data you need before rendering: the page title, a not-found check, a redirect.
Waiting for fresh data: fetchEntry
const [handles, data] = await loadHandles(trpc, {
post: fetchEntry(trpc.post.byId, { id }),
});- It works like
ensureEntry, with one difference: if the cache has stale data, it refetches and waits for the new data, likequeryClient.fetchQuery. - Use it when the loader reads the data and needs it fresh, for example a loader that redirects based on the post.
- In a browser loader, prefer
ensureEntry. With stale data, an ensure entry renders the page at once and updates it when the refetch lands. A fetch entry holds up the navigation until the refetch is done. - TanStack Router hides this difference on a page it has visited: by default, it shows the page with its last loader data and reruns the loader in the background. To wait there too, as the demo below does, set the router's
defaultStaleReloadMode, or a loader'sstaleReloadMode, to'blocking'. - In server components, the two behave the same: the request's
QueryClientstarts empty, so both wait for the request.
Which to use
prefetchEntry | ensureEntry | fetchEntry | |
|---|---|---|---|
| Page waits for data | No | Yes | Yes |
In data | No | Yes | Yes |
| With stale data | Refetches in the background | Resolves at once, refetches in the background | Waits for the refetch |
| Reader's first render | Loading state, or cached data | The data | The data |
| When the request fails | The reader gets the error | The load rejects, unless it had cached data | The load rejects |
The page shows at once, with skeletons until the data comes in. Stale data shows at once and refetches.
Comments
No requests yet.
TanStack Query equivalents
Each entry is one TanStack Query call with the procedure's queryOptions or infiniteQueryOptions. The load makes every call, then waits for the ones that aren't prefetches:
| tRPC | TanStack Query |
|---|---|
prefetchEntry(trpc.x, input, opts) | void queryClient.prefetchQuery(trpc.x.queryOptions(input, opts)) |
ensureEntry(trpc.x, input, opts) | await queryClient.ensureQueryData({ ...trpc.x.queryOptions(input, opts), revalidateIfStale: true }) |
fetchEntry(trpc.x, input, opts) | await queryClient.fetchQuery(trpc.x.queryOptions(input, opts)) |
prefetchInfiniteEntry, ensureInfiniteEntry, fetchInfiniteEntry | prefetchInfiniteQuery, ensureInfiniteQueryData (with revalidateIfStale: true), fetchInfiniteQuery |
fromHandle(trpc, handle, opts) | trpc.x.queryOptions(handle.input, opts), with x taken from the handle |
The queryClient is the one the proxy was created with. The entry names follow the TanStack Query method each one calls.
Waiting for some, streaming others
A page can wait for some queries and stream others. List them all in one load:
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
post: ensureEntry(trpc.post.byId, { id }),
});Here the post is ready when the page renders, and the comments stream in behind their own loading state. Both requests start together, whatever order you list them in.
Avoid awaiting one load and then starting another: the second load's requests wait for every entry the first one waited for. Use a second load only when its input comes from the first one's data: see Dependent queries.
Options
inputis optional when the procedure's input is optional, soprefetchEntry(trpc.viewer)works.optstakesstaleTime,gcTime,retry,retryDelay,meta, andtrpcrequest options such ascontext. They apply to the load's request. Readers use the options you pass tofromHandle.- Infinite entries also take
initialCursor, andpageswithgetNextPageParam: see Infinite queries.
Where to load handles
| Your app | Load handles in | With |
|---|---|---|
| Next.js App Router | Server components | The server proxy from trpc/server.tsx |
| TanStack Start, TanStack Router | Route loaders | The proxy in your router context |
| React Router | loader or clientLoader | See React Router |
| No loaders or server components, such as a SPA | Event handlers, such as a link's hover | useTRPC() |
loadHandlesand the entries take any tRPC options proxy: one fromcreateTRPCOptionsProxy, oruseTRPC(). Type a router context withTRPCOptionsProxy<AppRouter>.loadHandlestakes the root proxy,trpc, and one load can take entries from any procedure.- Load handles where the code can wait: a loader, a server component, or an event handler, such as preloading a page on hover. Don't call
loadHandlesduring render: every render starts its entries again, and a render can't wait for them. A component that renders before anything loaded its query reads it directly, withuseSuspenseQuery(trpc.x.queryOptions(input)).
Start every query from the URL
A loader or server component runs before anything renders, and all it has is the URL: the route's params, its search params, and on the server, the session. If every query a page needs takes its input from those, every request starts the moment the navigation does. No component has to render first to find out what to fetch.
- Path params name what the page is about:
/posts/$slug. - Search params hold everything else that changes what a query fetches: filters, sort, page. Keep them out of component state. A loader can't see component state, so the query would start only after render, the back button wouldn't restore the view, and a shared link would open the default one.
- Typesafe APIs without codegen▲ 3
- Streaming responses over HTTP▲ 40
- Subscriptions with server-sent events▲ 27
What the loader sees
loaderDeps: ({ search }) => search,
// { sort: 'new', page: 1 }
loader: ({ deps }) =>
loadHandles(trpc, {
posts: prefetchEntry(trpc.post.list, deps),
}),Requests
- loaderpost.list({ sort: 'new', page: 1 })done
If the URL isn't enough, reshape the procedure
If a page can't start a query from the URL alone, change the procedure, not the page. A procedure that takes an id you only learn from another query forces a waterfall on every page that calls it. Two fixes:
- Take what the URL has. Accept the slug or route param, and look up the id on the server.
- Return the joined data. Return the post with its author, not an author id for the client to look up.
The server sits next to the database, so the extra lookup costs a query there, not another round trip from the browser.
Before: the page is /posts/$slug, but the comments and the author need ids that only the post has:
import { z } from 'zod';
import { db } from './db';
import { t } from './trpc';
export const appRouter = t.router({
post: t.router({
bySlug: t.procedure
.input(z.object({ slug: z.string() }))
.query(({ input }) => db.post.bySlug(input.slug)),
comments: t.procedure
.input(
z.object({ postId: z.string(), cursor: z.number().nullish() }),
)
.query(({ input }) =>
db.comment.list({
postId: input.postId,
cursor: input.cursor ?? null,
}),
),
}),
author: t.router({
byId: t.procedure
.input(z.object({ id: z.string() }))
.query(({ input }) => db.author.byId(input.id)),
}),
});async function loader(params: { slug: string }) {
const [first, { post }] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.bySlug, { slug: params.slug }),
});
// Nothing below can start until the post has arrived
const [second] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, {
postId: post.id,
}),
author: prefetchEntry(trpc.author.byId, { id: post.authorId }),
});
return { ...first, ...second };
}post.bySlug |-------|
post.comments |-------|
author.byId |-------|
After: post.comments takes the slug, and post.bySlug returns the post with its author:
import { z } from 'zod';
import { db } from './db';
import { t } from './trpc';
export const appRouter = t.router({
post: t.router({
bySlug: t.procedure
.input(z.object({ slug: z.string() }))
.query(async ({ input }) => {
const post = await db.post.bySlug(input.slug);
return { ...post, author: await db.author.byId(post.authorId) };
}),
comments: t.procedure
.input(
z.object({ slug: z.string(), cursor: z.number().nullish() }),
)
.query(async ({ input }) => {
const post = await db.post.bySlug(input.slug);
return db.comment.list({
postId: post.id,
cursor: input.cursor ?? null,
});
}),
}),
});async function loader(params: { slug: string }) {
// Both start from the URL, together
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, {
slug: params.slug,
}),
post: ensureEntry(trpc.post.bySlug, { slug: params.slug }),
});
return handles;
}post.bySlug |-------|
post.comments |-------|
The page is ready after one round trip instead of two, and the loader no longer reads the post to start the other queries.
Reading a handle
fromHandle(trpc, handle, opts?) returns the same options as trpc.<path>.queryOptions(input, opts) for the handle's procedure and input, or trpc.<path>.infiniteQueryOptions(input, opts) for an infinite handle. Pass them to any TanStack Query hook or QueryClient method:
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, props.post));
const titleQuery = useQuery(fromHandle(trpc, props.post, { select: (post) => post.title }));
const [aQuery, bQuery] = useSuspenseQueries({
queries: [fromHandle(trpc, props.a), fromHandle(trpc, props.b)],
});optstakes everythingqueryOptionstakes, such asselect,staleTime,refetchIntervalandtrpc.fromHandletakes any level of the proxy:fromHandle(trpc, handle)andfromHandle(trpc.post, handle)behave the same.- Reads use the same query key as
trpc.<path>.queryOptions(input), so old and new code share cache entries. handle.queryKeyis the cache entry's key. For a typedqueryClient.getQueryData, passfromHandle(trpc, handle).queryKey. The handle's own key isn't tagged with its data type, so the handle stays serializable everywhere, including TanStack Router'sbeforeLoad.handle.inputis the typed input the query was started with, so a component doesn't need it as a separate prop. Infinite handles leave outcursoranddirection.
Typing props
Export your proxy type once, then type props with inferQueryHandle:
export type TRPC = TRPCOptionsProxy<AppRouter>;'use client';
import { useSuspenseQuery } from '@tanstack/react-query';
import { fromHandle } from '@trpc/tanstack-react-query/unstable-handles';
import type { inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { useTRPC, type TRPC } from '~/trpc/client';
export function Post(props: { post: inferQueryHandle<TRPC['post']['byId']> }) {
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, props.post));
return <h1>{postQuery.data.title}</h1>;
}A handle can only come from loadHandles. A raw input, an entry, or an object with the right queryKey and input written by hand, doesn't type-check. In tests, load one over a seeded cache: see Testing components that take handles. At runtime, fromHandle also throws a readable error for anything that isn't a handle, and when the handle's keyPrefix differs from the reading proxy's.
inferQueryHandle accepts a handle from any entry: they all have the same type.
Reading with useQuery
You don't need useSuspenseQuery or a Suspense boundary to read a handle. useQuery works with every handle, as for any query. Switch on its status to show each state:
'use client';
import { useQuery } from '@tanstack/react-query';
import { fromHandle } from '@trpc/tanstack-react-query/unstable-handles';
import type { inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { useTRPC, type TRPC } from '~/trpc/client';
export function Post(props: { post: inferQueryHandle<TRPC['post']['byId']> }) {
const trpc = useTRPC();
const postQuery = useQuery(fromHandle(trpc, props.post));
switch (postQuery.status) {
case 'pending':
return <p>Loading post…</p>;
case 'error':
return <p>Couldn't load the post: {postQuery.error.message}</p>;
case 'success':
return <h1>{postQuery.data.title}</h1>;
}
}useQuerydoesn't suspend. Until the data arrives, it renders withstatus: 'pending'.- After an ensure or fetch entry, the cache has the data, so the first render has
status: 'success'. - With server rendering, read a prefetch entry's handle with
useSuspenseQuery: withuseQuery, the server can render the loading state while the browser already has the data, and React reports a hydration mismatch (TanStack/query#9399). For a component onuseQuery, wait for the data instead, with an ensure entry.
Handles carry no data
A handle is only the query's key and input, whichever entry made it. The data lives in the cache, so the reader decides how to wait for it:
useSuspenseQuerytypesdataas defined. The component suspends until the cache has the data.useQuerytypesdataas possiblyundefined, as for any query. Switch onstatusto narrow it.
When the cache loses the data
Waiting for a query with an ensure or fetch entry puts its data in the cache before the reader renders. The cache can still lose that data later, and the reader then has to load it again:
queryClient.resetQueries()clears the data and refetches the queries on screen at once. AuseSuspenseQueryreader suspends and shows the nearestSuspensefallback. AuseQueryreader renders withstatus: 'pending'.queryClient.removeQueries()andqueryClient.clear(), for example on logout, drop the query from the cache. A reader on screen keeps its data until it renders again. Then it loads the query as above.- TanStack Query also drops a query no component has used for its
gcTime. A reader that mounts after that loads it again. queryClient.invalidateQueries()keeps the data and refetches in the background, so the reader shows no loading state.
So give every reader a loading state, even when the page waited for its data: put a useSuspenseQuery reader under a Suspense boundary, or handle 'pending' in a useQuery reader. Without a boundary of its own, a reader that suspends shows the fallback of the nearest boundary above it, which may cover the whole page.
The reader loads the query again with a new request. A handle doesn't bring back the data the loader started with.
This is how readers behave with the default options. Some options change it: with initialData, resetQueries() puts that data back, and with enabled: false, a reader that lost its data stays pending and starts no request.
Using the data in a loader
To use the data where you load it, for example to set the page title or redirect, read it from the load's data. It has the data of every ensure and fetch entry, by the entry's key:
const [handles, data] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
post: ensureEntry(trpc.post.byId, { id }),
});
if (!data.post.title) notFound();datahas no key for prefetch entries, since their query may have no data yet.- The data is the same object the cache holds. Return
handles, notdata, so it doesn't cross to the browser twice. - Don't build other queries' inputs from it. Start them from the URL instead, as in Start every query from the URL. Otherwise, see Dependent queries.
Infinite queries
The post page's comments and more by its author are lists, so they're infinite queries. For procedures with a cursor input, use prefetchInfiniteEntry, ensureInfiniteEntry and fetchInfiniteEntry. They load the first page. To load more pages up front, pass pages with getNextPageParam:
const [handles, data] = await loadHandles(trpc, {
comments: ensureInfiniteEntry(
trpc.post.comments,
{ postId: id, limit: 20 },
{ pages: 3, getNextPageParam: (last) => last.nextCursor },
),
});
data.comments.pages;pages applies when the cache has no pages for the query. If it already has some, an ensure entry resolves with those, and if a request for the query is already in flight, the entry joins it and gets the pages that request loads. Two entries for the same query share one cache entry, so list each query once.
Functions can't cross to the client, so pass getNextPageParam when you read an infinite handle:
const commentsQuery = useSuspenseInfiniteQuery(
fromHandle(trpc, props.comments, {
getNextPageParam: (last) => last.nextCursor,
}),
);Type the prop with inferInfiniteQueryHandle<TRPC['post']['comments']>.
In the browser, a loader can run again while the cache holds every page the user loaded. If that data is stale, the entry refetches all of those pages, which needs getNextPageParam from page two on. Pass the reader's getNextPageParam to entries in loaders that run in the browser:
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(
trpc.post.comments,
{ postId: id, limit: 20 },
{ getNextPageParam: (last) => last.nextCursor },
),
});Changing a handle's input
A handle names one input. When the user changes a list's sort or filter, put it in a search param: the loader then starts the new query and passes a new handle. Change the input in the component only when the URL can't hold it, such as a term the user is typing.
Say the post page's comments can be searched, and the loader starts them with an empty term: { postId: id, term: '' }. To read another input, call the procedure directly, starting from the handle's input:
import { useSuspenseInfiniteQuery } from '@tanstack/react-query';
import type { inferInfiniteQueryHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { useDeferredValue, useState } from 'react';
export function Comments(props: {
comments: inferInfiniteQueryHandle<typeof serverTRPC.post.comments>;
}) {
const trpc = useTRPC();
// Start from the loader's input, so the first render reads the query it started
const [term, setTerm] = useState(props.comments.input.term);
const deferredTerm = useDeferredValue(term);
const commentsQuery = useSuspenseInfiniteQuery(
trpc.post.comments.infiniteQueryOptions(
{ ...props.comments.input, term: deferredTerm },
{ getNextPageParam: (last) => last.nextCursor },
),
);
return (
<>
<label>
Search comments
<input value={term} onChange={(event) => setTerm(event.target.value)} />
</label>
<p>{commentsQuery.data.pages[0]?.items.length} comments</p>
</>
);
}- While the input matches the handle's,
infiniteQueryOptionsreturns the same query key, so the first render reads the loader's cache entry instead of fetching again. For a query handle, usetrpc.x.queryOptions({ ...handle.input, term })the same way. - A new term's query starts when the component renders with it, so its first page waits for that render.
useDeferredValuekeeps the previous results on screen while it loads. - Render
<Comments key={postId} … />, so moving to another post resets the term to the new handle's.
Request waterfalls
A request waterfall, the problem handles exist to avoid, is a request that can't start until another one has finished. Each level costs a full round trip, and on a slow connection a round trip can take hundreds of milliseconds, so removing waterfalls is often the best way to speed up a page.
With handles, queries start in loaders and server components, where everything a page needs is known from the URL, so they start together:
1. |-> post.byId
1. |-> post.comments
1. |-> post.moreByAuthor
instead of one after the other, as each component renders and finds out what it needs:
1. |-> post.byId
2. |-> post.comments
3. |-> post.byAuthor
The demo runs one blog both ways. Watch the network panel:
The route loader starts every query from the URL: the article's id, or the list's page. One round trip.
Comments
No requests yet.
To keep it that way:
- Load handles in loaders and server components, not in render.
- List every query in one load. See Waiting for some, streaming others.
- Make the URL the input, so the loader can start every query. See Start every query from the URL.
Dependent queries
A query whose input comes from another query's result is a waterfall by construction. Most pages don't need one: put the input in the route, or reshape the procedure so the page can start it from the URL. For example, trpc.post.moreByAuthor({ postId }) instead of trpc.post.byId and then trpc.post.byAuthor({ authorId }).
When the data really can't be reshaped, for example a third-party API you don't control, there are two explicit ways. Both pay the extra round trip.
In a loader or server component
Load the first query, then build the second load's entries from its data:
const [first, { post }] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
const [second] = await loadHandles(trpc, {
moreByAuthor: prefetchInfiniteEntry(trpc.post.byAuthor, {
authorId: post.authorId,
}),
});
const handles = { ...first, ...second };The page waits for the post, and more by its author starts only after it.
In a component
When an input is only known at render time, such as an id from a parent query's result, read the query in the component that gets the input, as MoreByAuthor does in the post page at the top:
const postsQuery = useSuspenseInfiniteQuery(
trpc.post.byAuthor.infiniteQueryOptions(
{ authorId },
{ getNextPageParam: (last) => last.nextCursor },
),
);- The query starts when
MoreByAuthorrenders, an extra round trip after its parent's data arrives. - In the Next.js App Router, load the dependent query in the server component instead, as in the loader example.
- In TanStack Router,
beforeLoadcan wait for the first query before the loader runs. It's an escape hatch, for when the dependent data must be there before the page renders: see TanStack Start › Handles inbeforeLoad.
React Router
React Router loads data in one of two places, and handles fit each a little differently. Route components pass handles from loaderData to the same client components as everywhere else.
Client-only apps
In SPA Mode (ssr: false) with clientLoader, or in Data Mode with createBrowserRouter, loaders run in the browser. Create the tab's QueryClient and proxy in a module, so loaders can import them, and provide the same client to your app:
import { QueryClient } from '@tanstack/react-query';
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query';
import type { AppRouter } from '~/server/router';
// Only in a client-only app: with server rendering, every request would share it
export const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 30_000 } },
});
export const trpcClient = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: '/api/trpc' })],
});
export const trpc = createTRPCOptionsProxy({ client: trpcClient, queryClient });import { Suspense } from 'react';
import { Comments } from '~/components/comments';
import { Post } from '~/components/post';
import { trpc } from '~/trpc';
import type { Route } from './+types/post';
import { loadHandles, ensureEntry, prefetchInfiniteEntry } from '@trpc/tanstack-react-query/unstable-handles';
export async function clientLoader({ params }: Route.ClientLoaderArgs) {
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: params.id, limit: 20 }),
post: ensureEntry(trpc.post.byId, { id: params.id }),
});
return handles;
}
export default function PostPage({ loaderData }: Route.ComponentProps) {
return (
<>
<Post post={loaderData.post} />
<Suspense key={loaderData.post.input.id} fallback={<p>Loading comments…</p>}>
<Comments comments={loaderData.comments} />
</Suspense>
</>
);
}In Data Mode, the same function is a route object's loader, and the component reads it with useLoaderData:
import { Suspense } from 'react';
import { createBrowserRouter, useLoaderData, type LoaderFunctionArgs } from 'react-router';
import { Comments } from '~/components/comments';
import { Post } from '~/components/post';
import { trpc } from '~/trpc';
import { loadHandles, ensureEntry, prefetchInfiniteEntry } from '@trpc/tanstack-react-query/unstable-handles';
async function postLoader({ params }: LoaderFunctionArgs) {
const id = params.id!;
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id, limit: 20 }),
post: ensureEntry(trpc.post.byId, { id }),
});
return handles;
}
function PostPage() {
const { comments, post } = useLoaderData<typeof postLoader>();
return (
<>
<Post post={post} />
<Suspense key={post.input.id} fallback={<p>Loading comments…</p>}>
<Comments comments={comments} />
</Suspense>
</>
);
}
export const router = createBrowserRouter([
{ path: '/posts/:id', loader: postLoader, Component: PostPage },
]);- There is nothing to hydrate: the loader starts queries in the same
QueryClientthe components read. - The ensure entry waits on the first visit only. Coming back shows the cached post at once and refetches it in the background if it's stale.
- Key
Suspenseboundaries by the route's input. React Router renders the next page in a transition, and a transition waits for a boundary that's already showing content instead of showing its fallback. Without the key, navigating from one post to another waits for the comments.
Server rendering
In Framework Mode with server rendering, loader runs on the server, for the first page load and for every navigation after it. Create a query client and proxy per request in a root middleware. Loaders return dehydrate(queryClient) with their handles, and the route component wraps its children in TanStack Query's HydrationBoundary, as with any TanStack Query loader:
import type { QueryClient } from '@tanstack/react-query';
import {
createTRPCOptionsProxy,
type TRPCOptionsProxy,
} from '@trpc/tanstack-react-query';
import { createContext } from 'react-router';
import { appRouter, type AppRouter } from '~/server/router';
import { makeQueryClient } from './query-client';
export const trpcContext = createContext<{
queryClient: QueryClient;
trpc: TRPCOptionsProxy<AppRouter>;
}>();
export function createServerTRPC() {
const queryClient = makeQueryClient();
const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient });
return { queryClient, trpc };
}import { QueryClientProvider } from '@tanstack/react-query';
import { createTRPCClient } from '@trpc/client';
import { useState } from 'react';
import { Outlet } from 'react-router';
import type { AppRouter } from '~/server/router';
import { TRPCProvider } from '~/trpc/client';
import type { Route } from './+types/root';
import { makeQueryClient } from './trpc/query-client';
import { createServerTRPC, trpcContext } from './trpc/server';
export const middleware: Route.MiddlewareFunction[] = [
({ context }) => {
context.set(trpcContext, createServerTRPC());
},
];
export default function App() {
const [queryClient] = useState(makeQueryClient);
const [trpcClient] = useState(() => createTRPCClient<AppRouter>({ links: [/* ... */] }));
return (
<QueryClientProvider client={queryClient}>
<TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
<Outlet />
</TRPCProvider>
</QueryClientProvider>
);
}import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { loadHandles, ensureEntry, prefetchInfiniteEntry } from '@trpc/tanstack-react-query/unstable-handles';
import { Suspense } from 'react';
import { Comments } from '~/components/comments';
import { Post } from '~/components/post';
import { trpcContext } from '../trpc/server';
import type { Route } from './+types/post';
export async function loader({ params, context }: Route.LoaderArgs) {
const { queryClient, trpc } = context.get(trpcContext);
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: params.id, limit: 20 }),
post: ensureEntry(trpc.post.byId, { id: params.id }),
});
return { dehydratedState: dehydrate(queryClient), ...handles };
}
export default function PostPage({ loaderData }: Route.ComponentProps) {
return (
<HydrationBoundary state={loaderData.dehydratedState}>
<Post post={loaderData.post} />
<Suspense key={loaderData.post.input.id} fallback={<p>Loading comments…</p>}>
<Comments comments={loaderData.comments} />
</Suspense>
</HydrationBoundary>
);
}makeQueryClientis the query client factory from the server components guide: it dehydrates pending queries and runs your transformer'sserializeanddeserialize.- React Router streams promises in loader data, so the comments' pending query crosses as a promise inside
dehydratedState. The page's HTML doesn't wait for it, and the browser doesn't fetch it again. dehydrate(queryClient)sends everything the request's client holds. Nested routes share it, so a query another loader started can be sent twice. Filter withdehydrate'sshouldDehydrateQueryif that matters.- Nested routes share the request's proxy, since the middleware runs once per request. A query that two loaders start is requested once.
- In a
loader, an ensure entry waits like a fetch entry, since the request'sQueryClientstarts empty. Use a prefetch entry for queries the page can stream.
Next.js App Router
This builds on the Next.js App Router setup. The query client factory, getQueryClient and the server proxy in trpc/server.tsx stay as they are. Add export type TRPC = TRPCOptionsProxy<AppRouter> to trpc/client.tsx, and in trpc/server.tsx, replace the setup's HydrateClient with one from unstable_createHydrateClient:
import { unstable_createHydrateClient } from '@trpc/tanstack-react-query';
// ... `getQueryClient` and the `trpc` proxy as before
export const HydrateClient = unstable_createHydrateClient(getQueryClient);The client components are the same either way: they read the handle with useSuspenseQuery or useQuery, as in Typing props.
HydrateClient
HydrateClient sends the queries the request has started so far to the browser, including pending ones, which stream in as they settle. Render one in each server component that starts queries for client components:
import { Suspense } from 'react';
import { HydrateClient, trpc } from '~/trpc/server';
import { Comments } from './comments';
import { Post } from './post';
import { loadHandles, prefetchEntry, prefetchInfiniteEntry } from '@trpc/tanstack-react-query/unstable-handles';
export default async function PostPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
const [{ post }] = await loadHandles(trpc, {
post: prefetchEntry(trpc.post.byId, { id }),
});
return (
<HydrateClient>
<Suspense fallback={<p>Loading post…</p>}>
<Post post={post} />
</Suspense>
<Suspense fallback={<p>Loading comments…</p>}>
<CommentsSection id={id} />
</Suspense>
</HydrateClient>
);
}
async function CommentsSection(props: { id: string }) {
const [{ comments }] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: props.id, limit: 20 }),
});
return (
<HydrateClient>
<Comments comments={comments} />
</HydrateClient>
);
}- A query an earlier
HydrateClientsent in the same request isn't sent again, so nesting them is fine. The outer one renders beforeCommentsSectionstarts its query, so each sends only its own. - A query is sent again when the server has newer data for it, for example after a fetch entry refetched it.
- It keeps your query client's
dehydrateoptions:shouldDehydrateQuery,serializeDataand the rest. - It works only in server components.
@trpc/tanstack-react-queryresolves to its server build through thereact-serverexport condition, which Next.js and other RSC bundlers set for server components. Rendered anywhere else, it throws. - It works for queries started with
queryClient.prefetchQuery(trpc.x.queryOptions(input))too, not only handles.
Streaming with prefetch entries
The page sends its HTML at once. Each Suspense boundary shows its fallback, then the data streams in:
import { Suspense } from 'react';
import { HydrateClient, trpc } from '~/trpc/server';
import { Comments } from './comments';
import { Post } from './post';
import { loadHandles, prefetchEntry, prefetchInfiniteEntry } from '@trpc/tanstack-react-query/unstable-handles';
export default async function PostPage(props: {
params: Promise<{ id: string }>;
}) {
const { id } = await props.params;
const [{ post, comments }] = await loadHandles(trpc, {
post: prefetchEntry(trpc.post.byId, { id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id, limit: 20 }),
});
return (
<HydrateClient>
<Suspense fallback={<p>Loading post…</p>}>
<Post post={post} />
</Suspense>
<Suspense fallback={<p>Loading comments…</p>}>
<Comments comments={comments} />
</Suspense>
</HydrateClient>
);
}- Give each handle its own
Suspenseboundary, so one slow query doesn't hold back the rest. - If the post doesn't exist, the
Postcomponent throws, and the nearesterror.tsxshows the error.
Waiting with ensure entries
The page waits for the post before it renders. Use this when the page can't render without the data, or when you need it on the server, for example to call notFound():
import {
ensureEntry,
isTRPCEntryError,
loadHandles,
} from '@trpc/tanstack-react-query/unstable-handles';
import { notFound } from 'next/navigation';
import { HydrateClient, trpc } from '~/trpc/server';
import { Post } from './post';
export default async function PostPage(props: {
params: Promise<{ id: string }>;
}) {
const { id } = await props.params;
const [{ post }] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
}).catch((cause) => {
if (isTRPCEntryError(cause, trpc.post.byId) && cause.code === 'NOT_FOUND') {
notFound();
}
throw cause;
});
return (
<HydrateClient>
<Post post={post} />
</HydrateClient>
);
}- The data is in the cache before
Postrenders, so it shows the post at once. If the cache loses the post later,Postsuspends and shows the nearestloading.tsxorSuspensefallback: see When the cache loses the data. - To use the data on the server, read it from the cache: see Using the data in a loader.
To wait for some queries and stream others on the same page, see Waiting for some, streaming others.
Handle inputs
Handle inputs cross to the client inside the handle, through React's own serialization, not your tRPC data transformer. This isn't new: dehydrated query keys already cross the same way. Keep inputs to plain JSON values and Dates. React can send a Map, Set or BigInt too, but TanStack Query hashes query keys with JSON.stringify: a BigInt input throws, and two different Map or Set inputs share one cache entry.
Errors
With ensure and fetch entries
When a request the load waits for fails, loadHandles rejects with a TRPCEntryError that says which entry it was. That's any fetch entry's request, and an ensure entry's when the cache had no data:
error.key: the entry's key, such as'post'.error.path: the procedure, such as'post.byId'.error.code: the tRPC error code, such as'NOT_FOUND'.error.cause: the request's error. That's aTRPCErroron the server proxy, and aTRPCClientErroron a client-backed proxy, such as one in a TanStack Start loader.
isTRPCEntryError(error, trpc.post.byId) checks that the failed entry was for that procedure, and types error.cause with its errors. In the post page at the top, only the post is awaited, so only the post can make the load reject. If the page waits for the comments too, chain .catch to check which one failed, so a missing post gets a 404:
import {
ensureEntry,
ensureInfiniteEntry,
isTRPCEntryError,
loadHandles,
} from '@trpc/tanstack-react-query/unstable-handles';
async function loader(id: string) {
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: ensureInfiniteEntry(trpc.post.comments, { postId: id }),
}).catch((error: unknown) => {
if (isTRPCEntryError(error, trpc.post.byId) && error.code === 'NOT_FOUND') {
notFound();
}
if (isTRPCEntryError(error, trpc.post.comments)) {
reportError(error.cause); }
throw error;
});
return handles;
}- The load rejects as soon as one entry fails, without waiting for the others. If several fail, you get the first to fail.
- Errors that don't come from the request, such as a cancelled query, reject as they are.
Errors as values
loadHandlesSettled takes the same entries, but never rejects because an entry failed. It waits for every fetch and ensure entry to settle, then resolves to [handles, results]. Each of those entries has { status: 'success', data } or { status: 'error', error } on results, with a TRPCEntryError:
import {
ensureEntry,
loadHandlesSettled,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
const [handles, results] = await loadHandlesSettled(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
if (results.post.status === 'error') {
if (results.post.error.code === 'NOT_FOUND') {
notFound();
}
throw results.post.error;
}
results.post.data.title;- It waits for every fetch and ensure entry, even after one has failed, so you see all their failures, not just the first.
resultshas no key for prefetch entries, asdatahasn't withloadHandles.handleshas a handle for every entry, failed or not. A component that reads a failed one gets the error, as with a prefetch entry.- A cancelled query still rejects, as with
loadHandles: the load was called off, so there's no result to give.
With prefetch entries
A prefetch entry never makes the load reject. The component that reads the handle gets the error instead: useQuery returns it as status: 'error', unless you pass throwOnError, and useSuspenseQuery throws it to the nearest error boundary unless it has cached data to show. It gets the query's own error, not a TRPCEntryError: the boundary already knows which handle it wraps.
import { isTRPCClientError } from '@trpc/client';
import { Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { Comments } from '~/components/comments';
import type { AppRouter } from '~/server/router';
function CommentsError(props: { error: unknown }) {
if (isTRPCClientError<AppRouter>(props.error)) {
return <p>Couldn't load the comments ({props.error.data?.code}).</p>;
}
throw props.error;
}
export function PostComments(props: {
comments: inferInfiniteQueryHandle<TRPC['post']['comments']>;
}) {
return (
<ErrorBoundary fallbackRender={CommentsError}>
<Suspense fallback={<p>Loading comments…</p>}>
<Comments comments={props.comments} />
</Suspense>
</ErrorBoundary>
);
}In the browser, that's a TRPCClientError:
- If the query failed before it was dehydrated, it isn't sent. The browser fetches it again and gets a
TRPCClientError. - If it was dehydrated while pending and failed later, TanStack Query passes a redacted error to the browser. A handle read then refetches the query once, even with
retry: false, so error boundaries get aTRPCClientErrorwithdata.code. A query that always fails costs one extra request.
To log or report these errors in one place, whichever component reads the handle, use the onError callback of your QueryClient's QueryCache.
Invalidation and staleness
Handle reads use normal tRPC query keys, so invalidation doesn't change. Pass any of these to queryClient.invalidateQueries:
{ queryKey: handle.queryKey }matches the handle's own query, plain or infinite.trpc.post.pathFilter()matches every query underpost, plain and infinite.trpc.post.byId.queryFilter(input)matches a query handle. An infinite handle's key hastype: 'infinite', soqueryFiltermisses it: usetrpc.post.comments.infiniteQueryFilter(input).
To update a handle's data in place, build its key from the procedure and handle.input: trpc.post.byId.queryKey(handle.input), or infiniteQueryKey for an infinite handle. setQueryData then checks the data's type. handle.queryKey is a plain array, so that the handle serializes, and carries no data type.
queryClient.setQueryData(trpc.post.byId.queryKey(handles.post.input), (post) =>
post ? { ...post, title: 'Renamed' } : post,
);
queryClient.setQueryData(
trpc.post.comments.infiniteQueryKey(handles.comments.input),
(comments) =>
comments && {
...comments,
pages: comments.pages.slice(0, 1),
pageParams: comments.pageParams.slice(0, 1),
},
);fromHandle keeps TanStack Query's refetch defaults. Hydrated data keeps the server's fetch time, so set a staleTime above 0 in your query client, as the setup guides do, or the client refetches right after hydration. To change it for one read, pass staleTime to fromHandle.
What a handle guarantees
- Types: only
loadHandlescreates handles. The key, procedure, input and kind (query or infinite) always agree, and output,selectand error types flow to the read. - Runtime:
fromHandlechecks the handle's shape andkeyPrefix.loadHandlesrejects an entry built with a proxy for anotherQueryClient. - Development: if a handle's query runs during server rendering, its data never reached that
QueryClient. tRPC logs a warning once per query. The warning is off in production.
Handles aren't signed. A handle names a query the browser could call anyway, and every refetch runs input validation and auth on the server again. Put permission checks in your procedures.
Testing components that take handles
Handles can't be written by hand, so create them in the test with a proxy over a test QueryClient. Seed the cache with fixture data, then load the handle with a prefetch entry, which leaves fresh data alone. The reader finds the fixture without calling the procedure:
import { QueryClient } from '@tanstack/react-query';
import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query';
import { loadHandles, prefetchEntry } from '@trpc/tanstack-react-query/unstable-handles';
import { appRouter } from './router';
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: Infinity, retry: false } },
});
const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient });
queryClient.setQueryData(trpc.post.byId.queryKey({ id: '1' }), {
id: '1',
title: 'Hello',
});
const [{ post }] = await loadHandles(trpc, {
post: prefetchEntry(trpc.post.byId, { id: '1' }),
});- Render the component under a
QueryClientProviderandTRPCProviderwith the samequeryClient. The component reads the fixture from the cache. - Leave out
setQueryDatato run the real procedure, or use a client withlocalLinkinstead ofrouterto test through your links. - For a loading state, leave out
setQueryDataand use a procedure that never resolves: the reader suspends.
Where handles don't work
- Server functions and server actions: they run with a
QueryClientthat never hydrates the page. Return data from them, not handles. - URLs and storage: a handle in the URL or
localStoragegains nothing over the input itself.
FAQ
Why functions instead of methods on trpc?
The methods on trpc, such as queryOptions, queryKey and pathFilter, return plain TanStack Query options, keys or filters. Handles are tRPC helpers built on top of them, so they're separate functions from @trpc/tanstack-react-query/unstable-handles that take a procedure: ensureEntry(trpc.post.byId, { id }). Apps that don't use handles don't load their code. Each entry is one TanStack Query call: see TanStack Query equivalents.
Why one load call instead of a call per query?
So a loader can't create a waterfall by the order of its lines. With a call per query, awaiting the post before starting the comments makes the comments wait for the post, and nothing warns you. A load starts every entry before it waits for any, whatever order you list them in. It also gives you the typed data of the entries it waited for, so a loader can check it without reading the cache. The cost is one load call and one entry, even for a loader that loads a single query.