Skip to content
Source
Sign inSign up
TanStack/query

feat(query-core, react-query): add experimental query handles #12512

DraftKATT(GitHub profile, opens in a new tab)wants to merge 30 commits intomain fromrefs/pull/12512/headopened View on GitHub

KATT(GitHub profile, opens in a new tab)commented

Note

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 queryFn and staleTime have 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 the queryFn rejects at once or throws synchronously; fetch errors show up where a component reads the handle.
  • experimental_queryHandleAsync(queryClient, factory, input) waits for fresh data like queryClient.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 throw notFound() 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 like select.
  • Types: experimental_QueryHandle, experimental_DefinedQueryHandle, experimental_QueryHandleFactory, experimental_FromHandleOptions and experimental_InferQueryHandleData. experimental_queryHandleAsync and experimental_ensureQueryHandle return an experimental_DefinedQueryHandle, and experimental_getQueryHandleData takes 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, or queryClient.infiniteQuery for options with an initialPageParam, and follow staleTime the 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: useSuspenseQuery gives defined data, and useQuery types data as possibly undefined, as usual.
  • select infers both at the read site and inside the factory; a read-site select replaces the factory's. experimental_InferQueryHandleData gives the same type as useSuspenseQuery's data, including select and InfiniteData.
  • 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 useState starts from the handle's input reads the loader's query on its first render.
  • A handle's type comes from its factory's key, so as const keys 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's queryOptions(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_ensureQueryHandle with an empty cache, stale cached data (the reader refetches on mount), cached infinite pages and a failed fetch, no unhandled rejection when a queryFn rejects at once or throws synchronously, a custom queryKeyHashFn, infinite factories, plain handles with no data, and a reader with no data after queryClient.clear(). experimental_getQueryHandleData reads awaited and stale ensured data without fetching, applies the factory's select, uses its queryKeyHashFn, and lets a loader throw a 404 for a missing post.
  • react-query queryHandles.test.tsx streams a pending query from experimental_queryHandle through dehydrate and HydrationBoundary to a useSuspenseQuery reader that doesn't fetch it again. It also checks that useQuery gets an awaited handle's data on the first render, and that a search box whose useState starts 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.tsx and trpcLikeProxy.test-d.tsx: inputs, keys that keep factories apart, data for every hook and start function, select at the read site and in the factory, experimental_InferQueryHandleData against useSuspenseQuery's data, defined handles from the two awaited verbs, and experimental_getQueryHandleData rejecting 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 $getQueryHandleData reads 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, subscribe and unmountOnDispose.

✅ 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:types across 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. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Draft PR not reviewed

      Draft PRs are not automatically reviewed by default.

      • Trigger a manual review

      To automatically review draft PRs, update your CodeRabbit configuration:

      reviews:
        auto_review:
          drafts: true
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      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

    2. changeset-bot[bot](GitHub profile, opens in a new tab)commented

      🦋 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
      NameType
      @tanstack/query-coreMinor
      @tanstack/react-queryMinor
      @tanstack/angular-query-experimentalMinor
      @tanstack/lit-queryPatch
      @tanstack/preact-queryMinor
      @tanstack/query-async-storage-persisterMinor
      @tanstack/query-broadcast-client-experimentalMinor
      @tanstack/query-devtoolsMinor
      @tanstack/query-persist-client-coreMinor
      @tanstack/query-sync-storage-persisterMinor
      @tanstack/solid-queryMinor
      @tanstack/svelte-queryPatch
      @tanstack/vue-queryMinor
      @tanstack/react-query-devtoolsMinor
      @tanstack/react-query-next-experimentalMinor
      @tanstack/react-query-persist-clientMinor
      @tanstack/preact-query-devtoolsMinor
      @tanstack/preact-query-persist-clientMinor
      @tanstack/solid-query-devtoolsMinor
      @tanstack/svelte-query-devtoolsPatch
      @tanstack/vue-query-devtoolsPatch
      @tanstack/solid-query-persist-clientMinor
      @tanstack/svelte-query-persist-clientPatch
      @tanstack/eslint-plugin-queryMinor

      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

    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      🤖 Nx Cloud AI Fix Eligible

      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.

      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)

      View your CI Pipeline Execution ↗ for commit b6bc2963405d1d88787be17d679006a458a440af

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...❌ Failed7m 5sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded40sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-11-03 21:50:17 UTC

    4. Wanna test out the branch so approved the workflows to get a pkg.pr.new link

    5. More templates

      @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@12512

      commit: b6bc296

    6. DogPawHat 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 client
      161+ .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 }
      DogPawHatcommented

      Would it be stupid to hash the input and the the queryFn source 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 postQuery handle to commentsQuery is a type error. tRPC (docs) and raf-query do the same.

      A queryFn source 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.

      I freaking love TypeScript

      @@ -0,0 +176,21 @@
      176+ * Starts a query without waiting and returns a serializable handle for it. A route loader, server
      177+ * component or server render passes the handle to the component that reads the query. Like
      178+ * `queryClient.query`, it fetches only if the cache has no fresh data. It doesn't reject: fetch
      179+ * 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+ * @example
      185+ * ```ts
      186+ * 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 loader
      193+ * const post = experimental_prefetchHandle(queryClient, postQuery, { id })
      194+ * ```
      195+ */
      196+export function experimental_prefetchHandle<
      DogPawHatcommented

      I think like with the unified imperative methods (query and infiniteQuery) we shouldn't be using 3 diffent handle factorys to do the same thing

      How does experimental_queryHandle that returns { handle, queryPromise }, where queryPromise is just the return from queryClient.query?

      (🤖 AI-assisted, but composed by me.)

      All three already make one queryClient.query call each. I don't know why ensureQueryData was deprecated. It was my favorite, since it gives stale-while-revalidate and fetchQuery doesn't. So I'd like to keep experimental_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_prefetchHandle never rejects.

      If you need the promise: queryClient.query(experimental_fromHandle(factory, handle)).

      KATT(GitHub profile, opens in a new tab)commented

      (🤖 AI-assisted, but composed by me.)

      To clarify how the data reaches the browser: the handle never carries it. The query cache does.

      1. The loader starts the query. The handle holds only { queryKey, input }.
      2. The pending query streams to the browser with the cache:
      3. A useSuspenseQuery(experimental_fromHandle(...)) reader in the browser picks up the streamed result and doesn't fetch again.

      So a queryPromise in 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 retry options. #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 revaliateIfStale option

      If 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

      (queryFactoryWithStaticTime does look ugly and I"m gonna hack on the idea of either trying to get away with plain queryOptions objects or some sort of deep FP psychosis to make it more elegant)

      KATT(GitHub profile, opens in a new tab)commented

      (🤖 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's experimental_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_queryHandleAsync or experimental_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_ensureQueryHandle uses 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.query with staleTime: 'static', so the factory keeps its real staleTime and you don't need a queryFactoryWithStaticTime.

      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 await line above comments makes 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, fetchQuery and ensureQueryData.
      • Typed in the loader. data does the job of experimental_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?

    1. Pushedd39c8f5

Sign in to join this conversation.