feat(query-core, react-query): add experimental query handles #12512
main fromrefs/pull/12512/head·opened View on GitHubNote
We made this PR with AI help and haven't yet done the two steps in TanStack's AI Contribution Policy. We still need to check that we understand all the code, and to rewrite this description in our own words.
Important
There's an alternative API in KATT/react-query#8 that I now prefer: one experimental_loadQueryHandles call with prefetch, fetch and ensure entries, which makes loader waterfalls hard by design. My reply on this PR explains why. Feedback on which to go with is welcome there.
To see the idea in action, try tRPC's live demo. It switches a blog's loaders between prefetching, ensuring and fetching, so you can see what each one waits for.
Motivation#
A route loader (such as TanStack Router's loader) or a Server Component already knows which data a page needs before the page renders, so it prefetches. Today the component that reads the data then has to repeat the query's key and options:
- The loader and the component each build the same key. If they drift apart, the read misses the prefetched data and fetches again, and nothing warns you. The component can even read a different query and still type-check.
- Options like
queryFnandstaleTimehave to match in both places, or the loader and the component disagree on how to fetch.
Query handles make the loader's call the single source of truth. The loader starts a query and returns a small serializable handle; the component gets the handle from Route.useLoaderData() and doesn't repeat the key or the options. A query whose input you only know during render doesn't need a handle: the component calls the factory with that input, which builds the same key.
Usage#
// A factory: one input in, query options out
const postQuery = (input: { id: string }) =>
queryOptions({
queryKey: ['post', input.id] as const,
queryFn: () => fetchPost(input.id),
})
const commentsQuery = (input: { postId: string }) =>
infiniteQueryOptions({
queryKey: ['comments', input.postId] as const,
queryFn: ({ pageParam }) =>
fetchComments({ postId: input.postId, page: pageParam }),
initialPageParam: 1,
getNextPageParam: (_lastPage, allPages) => allPages.length + 1,
})
const authorPostsQuery = (input: { authorId: string }) =>
infiniteQueryOptions({
queryKey: ['posts', 'by-author', input.authorId] as const,
queryFn: ({ pageParam }) =>
fetchPostsByAuthor({ authorId: input.authorId, page: pageParam }),
initialPageParam: 1,
getNextPageParam: (_lastPage, allPages) => allPages.length + 1,
})
// The loader starts the queries and returns handles: { queryKey, input }.
// It gets queryClient from createRouter({ routeTree, context: { queryClient } })
export const Route = createFileRoute('/posts/$id')({
loader: async ({ context: { queryClient }, params }) => ({
// Doesn't wait
comments: experimental_queryHandle(queryClient, commentsQuery, {
postId: params.id,
}),
// Waits for a cached post, even a stale one, or fetches it
post: await experimental_ensureQueryHandle(queryClient, postQuery, {
id: params.id,
}),
}),
component: PostPage,
})
function PostPage() {
const { post, comments } = Route.useLoaderData()
return (
<article>
<Title post={post} />
<Comments comments={comments} />
<MorePosts post={post} />
</article>
)
}
// Components read handles: no keys or inputs to repeat, and typed data
function Title(props: { post: experimental_QueryHandle<typeof postQuery> }) {
const { data: title } = useSuspenseQuery({
...experimental_fromHandle(postQuery, props.post),
select: (post) => post.title,
})
return <h1>{title}</h1>
}
// An infinite factory's handle reads with the infinite hooks
function Comments(props: {
comments: experimental_QueryHandle<typeof commentsQuery>
}) {
const { data, fetchNextPage } = useSuspenseInfiniteQuery(
experimental_fromHandle(commentsQuery, props.comments),
)
return <button onClick={() => fetchNextPage()}>{data.pages.length}</button>
}
// An input from another query's data is a waterfall: call the factory here
function MorePosts(props: { post: experimental_QueryHandle<typeof postQuery> }) {
const { data: post } = useSuspenseQuery(
experimental_fromHandle(postQuery, props.post),
)
const { data } = useInfiniteQuery(
authorPostsQuery({ authorId: post.authorId }),
)
return (
<ul>
{data?.pages.flat().map((p) => <li key={p.id}>{p.title}</li>)}
</ul>
)
}
// Type a prop that takes a query's data
function Byline(props: {
post: experimental_InferQueryHandleData<typeof postQuery>
}) {
return <span>{props.post.author}</span>
}
Integrations#
tRPC shipped the same idea in its own package as unstable_$prefetch, unstable_$ensure, unstable_$fetch and unstable_$fromHandle (trpc/trpc#7759). Its Prefetching with handles guide has the live demo linked above. With handles in query-core, an integration doesn't need its own version. A procedure's options function is already a factory, so an integration only adds a way to find the factory from a handle's key, and readers stop naming the procedure. trpcLikeProxy.test.tsx builds such a proxy on the public API alone: it starts queries on the server, sends the handles through dehydrate and JSON, and reads them in the browser without naming the procedure again.
🎯 Changes#
query-core adds these as experimental_ APIs, and react-query re-exports them. Every existing API works as before.
API#
experimental_queryHandle(queryClient, factory, input)starts a query without waiting and returns its handle. It never rejects, even when thequeryFnrejects at once or throws synchronously; fetch errors show up where a component reads the handle.experimental_queryHandleAsync(queryClient, factory, input)waits for fresh data likequeryClient.query, then resolves with the handle. It rejects when the query fails, so a loader can redirect or show an error page.experimental_ensureQueryHandle(queryClient, factory, input)waits for any data, even stale data. See below.experimental_getQueryHandleData(queryClient, factory, handle)reads an awaited handle's data from the cache, typed by the factory, so a loader can thrownotFound()or redirect. It never fetches, waits or creates a query.experimental_fromHandle(factory, handle)returns the factory's options for the handle's input and adds nothing. Spread it to add read-site options likeselect.- Types:
experimental_QueryHandle,experimental_DefinedQueryHandle,experimental_QueryHandleFactory,experimental_FromHandleOptionsandexperimental_InferQueryHandleData.experimental_queryHandleAsyncandexperimental_ensureQueryHandlereturn anexperimental_DefinedQueryHandle, andexperimental_getQueryHandleDatatakes only that. The brand exists only in types.
Using cached data, even if stale#
queryClient.query with staleTime: 'static' replaces the deprecated ensureQueryData. experimental_ensureQueryHandle is its handle version:
const post = await experimental_ensureQueryHandle(queryClient, postQuery, { id })
It resolves at once with any cached post, even a stale one, and fetches and waits only when the cache has none. The reader uses the factory's staleTime, so it refetches stale data in the background on mount. The other two verbs keep queryClient.query's defaults.
Reading awaited data in a loader#
loader: async ({ context: { queryClient }, params }) => {
const comments = experimental_queryHandle(queryClient, commentsQuery, {
postId: params.id,
})
const post = await experimental_ensureQueryHandle(queryClient, postQuery, {
id: params.id,
})
if (!experimental_getQueryHandleData(queryClient, postQuery, post)) {
throw notFound()
}
return { post, comments }
},
The loader starts comments before it awaits, so they load in parallel. Passing a handle from experimental_queryHandle to experimental_getQueryHandleData is a type error, because its query may not have data yet. The data stays in the cache, so it reaches the browser once.
Behavior#
- The start functions call
queryClient.query, orqueryClient.infiniteQueryfor options with aninitialPageParam, and followstaleTimethe same way on server and browser clients. - Every handle is a plain
{ queryKey, input }and carries no data. Readers get the data from the cache:useSuspenseQuerygives defined data, anduseQuerytypesdataas possiblyundefined, as usual. selectinfers both at the read site and inside the factory; a read-siteselectreplaces the factory's.experimental_InferQueryHandleDatagives the same type asuseSuspenseQuery'sdata, includingselectandInfiniteData.- A component that only knows an input during render, like a search term the user types, calls the factory with it. The same input builds the same key, so a search box whose
useStatestarts from the handle'sinputreads the loader's query on its first render. - A handle's type comes from its factory's key, so
as constkeys keep handles from different factories apart. Only the types check this. The start functions take only the factory's input; passing a factory's extra parameters, like tRPC'squeryOptions(input, opts?), is a type error, because the handle couldn't carry them.
Docs#
A new guide, framework/react/guides/query-handles, covers the API above, using cached data even if stale with experimental_ensureQueryHandle, reading awaited data in a loader (with a warning not to build other queries' inputs from it), queries whose input you only know during render (plain factory calls for the author's posts and a search box), loader pitfalls (awaiting handles one after another, starting a handle after an await), streaming pending queries through shouldDehydrateQuery, server staleTime (with staleTime: 0 the browser refetches on mount), and nested dehydration that sends each query once per request.
Tests#
- query-core
handles.test.tsx: the three start functions on browser and server clients,experimental_ensureQueryHandlewith an empty cache, stale cached data (the reader refetches on mount), cached infinite pages and a failed fetch, no unhandled rejection when aqueryFnrejects at once or throws synchronously, a customqueryKeyHashFn, infinite factories, plain handles with no data, and a reader with no data afterqueryClient.clear().experimental_getQueryHandleDatareads awaited and stale ensured data without fetching, applies the factory'sselect, uses itsqueryKeyHashFn, and lets a loader throw a 404 for a missing post. - react-query
queryHandles.test.tsxstreams a pending query fromexperimental_queryHandlethroughdehydrateandHydrationBoundaryto auseSuspenseQueryreader that doesn't fetch it again. It also checks thatuseQuerygets an awaited handle's data on the first render, and that a search box whoseuseStatestarts from a handle's input reads the loader's query without fetching it again, then fetches once for a new term. - Type tests in
queryHandles.test-d.tsxandtrpcLikeProxy.test-d.tsx: inputs, keys that keep factories apart, data for every hook and start function,selectat the read site and in the factory,experimental_InferQueryHandleDataagainstuseSuspenseQuery'sdata, defined handles from the two awaited verbs, andexperimental_getQueryHandleDatarejecting handles that weren't awaited or that belong to another factory. trpcLikeProxy.test.tsx: the tRPC-like proxy described above. It has a$verb for each start function, and$getQueryHandleDatareads an awaited handle's data without naming the procedure.- The new tests clean up with
using. This PR adds four small helpers for that to@tanstack/query-test-utils, each with a test:fakeTimers,clearOnDispose,subscribeandunmountOnDispose.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested code changes locally with
pnpm run test:pr, or these tests do not apply to this pull request. (Ran oxlint, knip,test:typesacross all TS versions, and vitest for query-core, react-query and query-test-utils, plus the docs link check.) - I have followed the AI contribution policy and fully understand the code in this pull request, including any code generated with AI assistance.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
- 1
🦋 Changeset detected#
Latest commit: d39c8f500a74e90fc795c090bf03ef11c0cea6e2
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 24 packages
Name Type @tanstack/query-core Minor @tanstack/react-query Minor @tanstack/angular-query-experimental Minor @tanstack/lit-query Patch @tanstack/preact-query Minor @tanstack/query-async-storage-persister Minor @tanstack/query-broadcast-client-experimental Minor @tanstack/query-devtools Minor @tanstack/query-persist-client-core Minor @tanstack/query-sync-storage-persister Minor @tanstack/solid-query Minor @tanstack/svelte-query Patch @tanstack/vue-query Minor @tanstack/react-query-devtools Minor @tanstack/react-query-next-experimental Minor @tanstack/react-query-persist-client Minor @tanstack/preact-query-devtools Minor @tanstack/preact-query-persist-client Minor @tanstack/solid-query-devtools Minor @tanstack/svelte-query-devtools Patch @tanstack/vue-query-devtools Patch @tanstack/solid-query-persist-client Minor @tanstack/svelte-query-persist-client Patch @tanstack/eslint-plugin-query Minor Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR
🤖 Nx Cloud AI Fix Eligible#
To disable these notifications, a workspace admin can disable them [in workspace settings.](https://cloud.nx.app/orgs/6412ca9d1c251d000efa21ba/workspaces/6412c827e6da5d7b4a0b1fe3/settings/self-healing-ci?utm_source=pull-request&utm_medium=comment)An automatically generated fix could have helped fix failing tasks for this run, but Self-healing CI is disabled for this workspace. Visit workspace settings to enable it and get automatic fixes in future runs.
View your CI Pipeline Execution ↗ for commit b6bc2963405d1d88787be17d679006a458a440af
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...❌ Failed 7m 5s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 40s View ↗
☁️ Nx Cloud last updated this comment at
2026-11-03 21:50:17UTCWanna test out the branch so approved the workflows to get a pkg.pr.new link
More templates
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-basic-persister
- @tanstack/query-example-angular-devtools-panel-angular-router
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-optimistic-updates
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-query-options-from-a-service-angular-router
- @tanstack/query-example-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-simple
- @tanstack/query-example-preact-algolia
- @tanstack/query-example-preact-auto-refetching
- @tanstack/query-example-preact-basic
- @tanstack/query-example-preact-basic-graphql-request
- @tanstack/query-example-preact-batching
- @tanstack/query-example-preact-chat
- @tanstack/query-example-preact-default-query-function
- @tanstack/query-example-preact-devtools-panel
- @tanstack/query-example-preact-infinite-query-with-max-pages
- @tanstack/query-example-preact-load-more-infinite-scroll-preact-iso
- @tanstack/query-example-preact-offline-preact-iso
- @tanstack/query-example-preact-optimistic-updates
- @tanstack/query-example-preact-pagination
- @tanstack/query-example-preact-playground
- @tanstack/query-example-preact-prefetching-preact-iso
- @tanstack/query-example-preact-rick-morty-preact-iso
- @tanstack/query-example-preact-shadow-dom
- @tanstack/query-example-preact-simple
- @tanstack/query-example-preact-ssr
- @tanstack/query-example-preact-ssr-streaming
- @tanstack/query-example-preact-star-wars-preact-iso
- @tanstack/query-example-preact-suspense
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-auto-refetching-nextjs-pages-router
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-react-batching
- @tanstack/query-example-react-chat
- @tanstack/query-example-react-contacts-react-router
- @tanstack/query-example-react-contacts-tanstack-router
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-react-eslint-legacy
- @tanstack/query-example-react-eslint-plugin-demo
- @tanstack/query-example-react-infinite-query-with-max-pages-nextjs-pages-router
- @tanstack/query-example-react-load-more-infinite-scroll-nextjs-pages-router
- @tanstack/query-example-react-nextjs
- @tanstack/query-example-react-nextjs-app-optimistic-updates
- @tanstack/query-example-react-nextjs-app-prefetching
- @tanstack/query-example-react-nextjs-suspense-streaming
- @tanstack/query-example-react-offline-react-router
- @tanstack/query-example-react-offline-tanstack-router
- @tanstack/query-example-react-pagination-nextjs-pages-router
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching-nextjs-pages-router
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-rick-morty-react-router
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars-react-router
- @tanstack/query-example-react-suspense
- @tanstack/query-example-solid-algolia
- @tanstack/query-example-solid-astro
- @tanstack/query-example-solid-auto-refetching-solid-start2
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-batching
- @tanstack/query-example-solid-chat
- @tanstack/query-example-solid-contacts-solid-router
- @tanstack/query-example-solid-contacts-tanstack-router
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-devtools-panel
- @tanstack/query-example-solid-offline-solid-router
- @tanstack/query-example-solid-offline-tanstack-router
- @tanstack/query-example-solid-optimistic-updates-solid-start2
- @tanstack/query-example-solid-pagination-solid-start2
- @tanstack/query-example-solid-playground
- @tanstack/query-example-solid-prefetching-solid-start2
- @tanstack/query-example-solid-rick-morty-solid-router
- @tanstack/query-example-solid-shadow-dom
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-solid-start-streaming
- @tanstack/query-example-solid-star-wars-solid-router
- @tanstack/query-example-solid-suspense
- @tanstack/query-example-svelte-algolia
- @tanstack/query-example-svelte-auto-refetching-sveltekit
- @tanstack/query-example-svelte-basic-graphql-request
- @tanstack/query-example-svelte-basic-sveltekit
- @tanstack/query-example-svelte-batching
- @tanstack/query-example-svelte-chat
- @tanstack/query-example-svelte-default-query-function
- @tanstack/query-example-svelte-infinite-query-with-max-pages-sveltekit
- @tanstack/query-example-svelte-load-more-infinite-scroll-sveltekit
- @tanstack/query-example-svelte-offline-sveltekit
- @tanstack/query-example-svelte-optimistic-updates-sveltekit
- @tanstack/query-example-svelte-pagination-sveltekit
- @tanstack/query-example-svelte-playground-sveltekit
- @tanstack/query-example-svelte-prefetching-sveltekit
- @tanstack/query-example-svelte-rick-morty-sveltekit
- @tanstack/query-example-svelte-shadow-dom
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr-sveltekit
- @tanstack/query-example-svelte-star-wars-sveltekit
- @tanstack/query-example-svelte-sveltekit
- @tanstack/query-example-vue-2.6-basic
- @tanstack/query-example-vue-2.7-basic
- @tanstack/query-example-vue-algolia
- @tanstack/query-example-vue-auto-refetching-nuxt4
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-basic-graphql-request
- @tanstack/query-example-vue-batching
- @tanstack/query-example-vue-chat
- @tanstack/query-example-vue-contacts-tanstack-router
- @tanstack/query-example-vue-contacts-vue-router
- @tanstack/query-example-vue-default-query-function
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-devtools-panel
- @tanstack/query-example-vue-infinite-query-with-max-pages-nuxt4
- @tanstack/query-example-vue-load-more-infinite-scroll-nuxt4
- @tanstack/query-example-vue-offline-tanstack-router
- @tanstack/query-example-vue-offline-vue-router
- @tanstack/query-example-vue-optimistic-updates-nuxt4
- @tanstack/query-example-vue-pagination-nuxt4
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-playground
- @tanstack/query-example-vue-prefetching-nuxt4
- @tanstack/query-example-vue-rick-morty-vue-router
- @tanstack/query-example-vue-shadow-dom
- @tanstack/query-example-vue-simple
- @tanstack/query-example-vue-simple-nuxt3
- @tanstack/query-example-vue-simple-nuxt4
- @tanstack/query-example-vue-star-wars-vue-router
- @tanstack/query-example-vue-suspense
- @tanstack/query-example-lit-algolia
- @tanstack/query-example-lit-auto-refetching
- @tanstack/query-example-lit-basic
- @tanstack/query-example-lit-basic-graphql-request
- @tanstack/query-example-lit-batching
- @tanstack/query-example-lit-chat
- @tanstack/query-example-lit-default-query-function
- @tanstack/query-example-lit-infinite-query-with-max-pages
- @tanstack/query-example-lit-load-more-infinite-scroll-lit-labs-router
- @tanstack/query-example-lit-offline-lit-labs-router
- @tanstack/query-example-lit-optimistic-updates
- @tanstack/query-example-lit-pagination
- @tanstack/query-example-lit-playground
- @tanstack/query-example-lit-prefetching-lit-labs-router
- @tanstack/query-example-lit-rick-morty-lit-labs-router
- @tanstack/query-example-lit-simple
- @tanstack/query-example-lit-ssr
- @tanstack/query-example-lit-star-wars-lit-labs-router
@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@12512@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@12512@tanstack/lit-query
npm i https://pkg.pr.new/@tanstack/lit-query@12512@tanstack/preact-query
npm i https://pkg.pr.new/@tanstack/preact-query@12512@tanstack/preact-query-devtools
npm i https://pkg.pr.new/@tanstack/preact-query-devtools@12512@tanstack/preact-query-persist-client
npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@12512@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@12512@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@12512@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@12512@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@12512@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@12512@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@12512@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@12512@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@12512@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@12512@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@12512@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@12512@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@12512@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@12512@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@12512@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@12512@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@12512@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@12512@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@12512commit:
b6bc296DogPawHat reviewed
Some comments
@@ -0,0 +152,21 @@152+ * @param client - The client whose cache to look in.153+ * @param options - Options a query factory returned.154+ * @returns The query, if the cache has it.155+ */156+function getQuery(157+ client: QueryClient,158+ options: QueryFactoryOptions,159+): Query<any, any, any, any> | undefined {160+ return client161+ .getQueryCache()162+ .get(client.defaultQueryOptions(options).queryHash)163+}164+165+/**166+ * Builds a handle.167+ * @param options - Options a query factory returned.168+ * @param input - The factory's input.169+ * @returns A handle with their key and the input.170+ */171+function toHandle(options: QueryFactoryOptions, input: unknown) {172+ return { queryKey: options.queryKey, input }Would it be stupid to hash the input and the the
queryFnsource together as an integrity check (since we can't ship a function over json unfortunaly)(🤖 AI-assisted, but composed by me.)
Not stupid! I went with types: a handle's type comes from its factory's key, so passing a
postQueryhandle tocommentsQueryis a type error. tRPC (docs) and raf-query do the same.A
queryFnsource hash would break, since server and browser bundles compile the same factory differently. And a handle only names a query the browser could start anyway.@@ -0,0 +176,21 @@176+ * Starts a query without waiting and returns a serializable handle for it. A route loader, server177+ * component or server render passes the handle to the component that reads the query. Like178+ * `queryClient.query`, it fetches only if the cache has no fresh data. It doesn't reject: fetch179+ * errors show up where a component reads the handle.180+ * @param queryClient - The client to start the query on.181+ * @param factory - The query factory, a function of the query's input that returns its options.182+ * @param input - The input to pass to the factory, if it takes one.183+ * @returns A handle with the query's key and input.184+ * @example185+ * ```ts186+ * const postQuery = (input: { id: string }) =>187+ * queryOptions({188+ * queryKey: ['post', input.id] as const,189+ * queryFn: () => fetchPost(input.id),190+ * })191+ *192+ * // in a route loader193+ * const post = experimental_prefetchHandle(queryClient, postQuery, { id })194+ * ```195+ */196+export function experimental_prefetchHandle<I think like with the unified imperative methods (
queryandinfiniteQuery) we shouldn't be using 3 diffent handle factorys to do the same thingHow does
experimental_queryHandlethat returns{ handle, queryPromise }, wherequeryPromiseis just the return fromqueryClient.query?(🤖 AI-assisted, but composed by me.)
All three already make one
queryClient.querycall each. I don't know whyensureQueryDatawas deprecated. It was my favorite, since it gives stale-while-revalidate andfetchQuerydoesn't. So I'd like to keepexperimental_ensureHandle, but I'm happy to drop it if you'd rather.I'd keep the promise out:
- Routers stream promises in loader data, so the data would cross twice (trpc/trpc#7822).
- An ignored promise that rejects is an unhandled rejection.
experimental_prefetchHandlenever rejects.
If you need the promise:
queryClient.query(experimental_fromHandle(factory, handle)).(🤖 AI-assisted, but composed by me.)
To clarify how the data reaches the browser: the handle never carries it. The query cache does.
- The loader starts the query. The handle holds only
{ queryKey, input }. - The pending query streams to the browser with the cache:
- TanStack Router's Query integration does this for you.
- With RSC, you dehydrate pending queries and pass them to
HydrationBoundary. React serializes promises across that boundary.
- A
useSuspenseQuery(experimental_fromHandle(...))reader in the browser picks up the streamed result and doesn't fetch again.
So a
queryPromisein loader data would send a second copy of the same data. tRPC's Prefetching with handles guide has a live demo of this flow.While testing this flow, we found that a hydrated pending query that rejects ignores the reader's current
retryoptions. #12511 fixes that on its own.I don't know why ensureQueryData was deprecated. It was my favorite, since it gives stale-while-revalidate and fetchQuery doesn't.
See https://github.com/TanStack/query/discussions/9135 and @TkDodo comments on how tricky it was to explain the old methods and the
revaliateIfStaleoptionIf you need the promise: queryClient.query(experimental_fromHandle(factory, handle)).
Ok yeah we could just do that.
So probably something like:
// read from cache if exists, otherwise, go fetch and wait for it const handle = await queryClient.experimental_queryHandle(queryClient, queryFactoryWithStaticTime, input); const data = await queryClient.experimental_fromHandle(queryFactoryWithStaticTime, input); // refetch in the background if data is older than 2 minutes void queryClient.query({ ...queryFactoryWithStatic(input), staleTime: 1000 * 60 * 2 })Is what you end up doing
(
queryFactoryWithStaticTimedoes look ugly and I"m gonna hack on the idea of either trying to get away with plainqueryOptionsobjects or some sort of deep FP psychosis to make it more elegant)(🤖 Drafted with Opus 5.5, then read and edited word by word by me.)
I think what you're after with
{ handle, queryPromise }is typed data in the loader, for example to throw a 404. That'sexperimental_getQueryHandleData:loader: async ({ context: { queryClient }, params }) => { const comments = experimental_queryHandle(queryClient, commentsQuery, { postId: params.id, }) const post = await experimental_ensureQueryHandle(queryClient, postQuery, { id: params.id, }) if (!experimental_getQueryHandleData(queryClient, postQuery, post)) { throw notFound() } return { post, comments } }It only takes handles you've awaited, from
experimental_queryHandleAsyncorexperimental_ensureQueryHandle. Any other handle is a type error. So the read never fetches or waits, and the data stays in the cache instead of crossing to the browser a second time in loader data.Thanks for the link on
ensureQueryData.experimental_ensureQueryHandleuses what's cached, even if stale, and waits only when nothing is cached. It has its own verb because it's what I use most in loaders:- Navigation doesn't block on a refetch. Stale data shows at once, and the reader refetches in the background when it mounts.
- The first visit still waits, so the page renders with data and SSR has something to send.
- It's
queryClient.querywithstaleTime: 'static', so the factory keeps its realstaleTimeand you don't need aqueryFactoryWithStaticTime.
Howeeeeveeeer... while writing this up, I built an API I like better, in KATT/react-query#8. A loader lists its queries as entries, and one call starts them all:
loader: async ({ context: { queryClient }, params }) => { const [handles, data] = await experimental_loadQueryHandles(queryClient, { comments: experimental_prefetchEntry(commentsQuery, { postId: params.id }), post: experimental_ensureEntry(postQuery, { id: params.id }), }) if (!data.post) throw notFound() return handles }The main reason I prefer it: it makes waterfalls hard by design. The load starts every entry before it waits for any, so you can't await the post before you've started the comments. In the first example, moving the
awaitline abovecommentsmakes the comments wait for the post, and nothing warns you.It's also:
- Explicit. Prefetch, fetch and ensure each have their own entry verb, named after
prefetchQuery,fetchQueryandensureQueryData. - Typed in the loader.
datadoes the job ofexperimental_getQueryHandleData, typed the same and still read from the cache. Reading a prefetch entry from it is a type error.
The tradeoff is ceremony: a loader that fetches one thing still needs a load call and an entry. Most real pages make more than one request, though, so I think it pays for itself.
What do you and the maintainers think: should TanStack/query#12512 switch to this API?
- 2
Pushedd39c8f5
Sign in to join this conversation.
Important
Draft PR not reviewed#
Draft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share