feat(react-query): compose query modes and tree-shake client operations on v6 #12714
query-v6 fromrefs/pull/12714/head·opened View on GitHub🎯 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 result | useQuery(post) | useQuery(query(post)) |
| Single query under a Suspense boundary | useSuspenseQuery(post) | useQuery(suspenseQuery(post)) |
| Paginated query with a pending result | useInfiniteQuery(pages) | useQuery(infiniteQuery(pages)) |
| Paginated query under a Suspense boundary | useSuspenseInfiniteQuery(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#
| Feature | v6 option | Pluggable option |
|---|---|---|
| Poll every three seconds | refetchInterval: 3000 | refetchInterval: refetchInterval(3000) |
| Select a title for one observer | select: (post) => post.title | select: [select, (post) => post.title] |
| Keep the previous page while fetching | placeholderData: keepPreviousData | placeholderData: placeholderData(keepPreviousData) |
| Serialize mutations for one scope | scope: { 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
| Workload | React Query v6 | React Query Pluggable | Change vs v6 |
|---|---|---|---|
| Read-only list | 9,159 B | 7,277 B | -1,882 B (-20.55%) |
| Paginated bookmarks | 10,636 B | 9,687 B | -949 B (-8.92%) |
| Selection, serial bookmarks and invalidation | 10,320 B | 9,685 B | -635 B (-6.15%) |
| Polling | 9,777 B | 8,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 testandpnpm run test:pron 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
- 2
- 3
Pushed83a2748
Pushed0e7b109
Pushed6cf36e6
Pushed4954cd3
Pushed15e9d54
Pushed1c9c8d8
Pushede2fb131
Pushed8a21fac
manudeli(GitHub profile, opens in a new tab) changed the title
manudeli(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.