Skip to content
Source
Sign inSign up
TanStack/query

feat(react-query): compose query modes and tree-shake client operations on v6 #12714

Closedmanudeli(GitHub profile, opens in a new tab)wants to merge 12 commits intoquery-v6 fromrefs/pull/12714/headopened View on GitHub

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

🎯 Changes

I want a screen that reads one query to pay for the code that read needs. This draft adds @tanstack/react-query-pluggable, an ESM adapter for React 19. It shares retry, cancellation, garbage collection, state helpers and environment managers with @tanstack/query-core. Optional observers, cache operations and polling enter the bundle through the imports that use them. The comparison uses the unchanged @tanstack/react-query from the query-v6 base.

ESM gives bundlers a static import graph, but methods on a constructed class can keep features reachable. I’m comfortable asking users to migrate to separate named imports when the app actually drops those implementations. I expect TypeScript and AI-assisted development to make more distributed APIs easier to find and migrate. That is a design assumption. The measurements below test the payload savings.

One hook, four query modes

Create a QueryClient and pass it to QueryClientProvider from the same package. A caller can choose how each useQuery invocation reads its data. Here post contains a query key and fetch function. pages also supplies initialPageParam and getNextPageParam.

Consumer@tanstack/react-query@tanstack/react-query-pluggable
Single query with a pending resultuseQuery(post)useQuery(query(post))
Single query under a Suspense boundaryuseSuspenseQuery(post)useQuery(suspenseQuery(post))
Paginated query with a pending resultuseInfiniteQuery(pages)useQuery(infiniteQuery(pages))
Paginated query under a Suspense boundaryuseSuspenseInfiniteQuery(pages)useQuery(suspenseQuery(infiniteQuery(pages)))

query is the same JavaScript function as queryOptions. useQuery(post) still works. The paginated result exposes data.pages, hasNextPage and fetchNextPage. Wrapping the options in suspenseQuery lets the nearest Suspense boundary handle an uncached read and the nearest error boundary handle a failed fetch without cached data. The dedicated hooks remain available. Both readers of the same query key use the same cached data.

Move client operations to named imports

QueryClient holds the caches, defaults and lifecycle state. Every operation on that client is a named export with the client as its first argument. Creating a client for useQuery can therefore leave out imperative fetching, writes and bulk invalidation.

Before, on query-v6

import { QueryClient } from '@tanstack/react-query'

const client = new QueryClient()
const post = await client.query(postOptions)
const cached = client.getQueryData(postOptions.queryKey)
client.setQueryData(postOptions.queryKey, updatedPost)
await client.infiniteQuery(pageOptions)
await client.invalidateQueries({ queryKey: ['posts'] })
const unsubscribe = client.getQueryCache().subscribe(onQueryEvent)

With the pluggable adapter

import {
  QueryClient, fetchQuery, fetchInfiniteQuery, getQueryCache,
  getQueryData, invalidateQueries, setQueryData,
} from '@tanstack/react-query-pluggable'

const client = new QueryClient()
const post = await fetchQuery(client, postOptions)
const cached = getQueryData(client, postOptions.queryKey)
setQueryData(client, postOptions.queryKey, updatedPost)
await fetchInfiniteQuery(client, pageOptions)
await invalidateQueries(client, { queryKey: ['posts'] })
const unsubscribe = getQueryCache(client).subscribe(onQueryEvent)

Defaults follow the same convention, for example setQueryDefaults(client, key, options). The provider handles mount and unmount. Integrations that manage a client directly use mountQueryClient(client), unmountQueryClient(client) and clearQueryClient(client).

Cache objects keep their own methods. getMutationCache(client).subscribe(listener) creates a cache on first access or returns the constructor-supplied cache. useMutation acquires the same cache automatically. The stock @tanstack/query-persist-client-core subscription calls client.getQueryCache() and client.getMutationCache() on the instance. A persistence integration for this adapter must use the named accessors and the adapter's hydrate and dehydrate.

Import option behavior where it is used

Featurev6 optionPluggable option
Poll every three secondsrefetchInterval: 3000refetchInterval: refetchInterval(3000)
Select a title for one observerselect: (post) => post.titleselect: [select, (post) => post.title]
Keep the previous page while fetchingplaceholderData: keepPreviousDataplaceholderData: placeholderData(keepPreviousData)
Serialize mutations for one scopescope: { id: 'orders' }scope: serialScope('orders')

The tuple preserves inline selector inference. An already typed selector can use select: select(getTitle). Mutations with the same scope ID run in order within a cache, including after dehydration and hydration. The three option factories (queryOptions, infiniteQueryOptions, and mutationOptions) specialize their TypeScript signatures and share one JavaScript identity function.

What reaches the browser?

Gzipped Query runtime

WorkloadReact Query v6React Query PluggableChange vs v6
Read-only list9,159 B7,277 B-1,882 B (-20.55%)
Paginated bookmarks10,636 B9,687 B-949 B (-8.92%)
Selection, serial bookmarks and invalidation10,320 B9,685 B-635 B (-6.15%)
Polling9,777 B8,559 B-1,218 B (-12.46%)

For the read-only app, whole-app gzip goes from 76,925 B to 75,107 B (−2.36%). The query-only build excludes MutationCache, the infinite observer, Suspense and unreferenced imperative operations. The bookmark apps include the mutation implementation.

Each push builds four production apps against both packages. The primary percentage uses the compressed Query runtime for that workload, including all retained query-core modules. The same comment also measures the whole app with React and React DOM. The build checks the isolated chunk against the module and export graph of the deployable app. Chromium exercises all eight apps, including real Suspense fallback, pagination, polling and mutation flows. Bundle comparison and interactive treemaps

The stock React package’s separate Brotli size-limit measurement is 12,703 → 12,714 B for the full entry (+11 B, +0.09%) and 8,391 → 8,396 B for the minimal entry (+5 B, +0.06%). Preview size-limit report

✅ Checklist

  • Followed the contributing guide.
  • Ran pnpm test and pnpm run test:pr on this revision. Ten Next.js example builds stopped on their first run for an upgrade notice and passed on retry. Nx reported 656 successful tasks in both final commands. The GitHub Test job passed.
  • 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 included a changeset for the experimental adapter and the new core export.
  • This change is docs/CI/dev-only (no release).
    1. Pushed83a2748

    2. Pushed0e7b109

    3. Pushed6cf36e6

    4. Pushed4954cd3

    5. Pushed15e9d54

    6. Pushed1c9c8d8

    7. Pushede2fb131

    8. Pushed8a21fac

Sign in to join this conversation.