feat: Treeshakable Query #12722
query-v6 fromrefs/pull/12722/head·opened View on GitHub🎯 Changes#
I want to be able to add one server-state feature to a route and pay for that feature when the route loads. A v6 app can already defer an entire bookmarks screen. Its ordinary query observer and client still reach mutation caching, polling, result projection, and bulk cache operations even when the first screen only reads a list. ESM gives a bundler the opportunity to remove unreachable code. The dependency graph determines how much it can remove.
This changes the published @tanstack/query-core and the Angular, Lit, Preact, React, Solid, Svelte, and Vue adapters. The client owns state. Operations are named, client-first imports. See the migration guide and the v6 imperative Query API discussion.
await query(client, postQueryOptions(42))
await invalidateQueries(client, { queryKey: ['posts'] })
Choosing what a component loads#
In React and Preact, useQuery requires a descriptor. Its factory selects the observer, return type, and render behavior. A regular reader can handle errors inline without pulling in Suspense or Error Boundary handling. A paginated reader includes its page controls. A variable-length group can still use useQueries or useSuspenseQueries. The other adapters retain their native entry points and use the same treeshakable core. Framework reader entries
const postQueryOptions = (id: number) => queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id), // Promise<Post>
})
function Article({ id }: { id: number }) {
const article = useQuery(postQueryOptions(id))
if (isSuccess(article)) return <h1>{article.data.title}</h1>
if (isLoadingError(article)) return <p>{article.error.message}</p>
return <Spinner />
}
const postSuspenseOptions = (id: number) => suspenseQueryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})
// Render under <Suspense fallback={<Spinner />}>.
function ArticleTitle({ id }: { id: number }) {
const { data } = useQuery(postSuspenseOptions(id))
return <h1>{data.title}</h1>
}
The predicates narrow the original result. A running Suspense query returns defined data. If the fetcher can be skipToken, its result can be undefined. The two pagination factories are infiniteQueryOptions and suspenseInfiniteQueryOptions. Typed query readers · Public type tests
A selector uses ordinary function-call syntax. Given fetchPost(id): Promise<Post>, the callback takes a Post, the reader returns its title, and the cache keeps the original post.
const postTitleOptions = (id: number) =>
queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
select: select((post) => post.title),
})
For pagination, the same hook returns pages and the controls to load the next page.
const infiniteQueryResult = useQuery(
infiniteQueryOptions({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}),
)
When a heterogeneous useQueries list includes a selector, preparing each entry with queryOptions gives the callback its input type. If an inline page fetcher depends on its inferred pageParam, a named fetcher or an explicit return type makes the page type available to the selector. Query options guide · Infinite queries guide
refetchInterval: refetchInterval(3000) brings in the scheduler. select, placeholderData, and serialScope work the same way. An ordinary React or Preact reader that needs an Error Boundary imports throwOnError and sets throwOnError: [throwOnError, true]. The second element also accepts a predicate. Structural sharing remains enabled by default. Selection and serial bookmarks · Polling
What leaves the bundle#
The Actions comment compares four React workloads to the published package entries built from the v6 baseline at dc33f10c. Percentages use the matching Query-only chunk as their denominator. React, React DOM, and application code are outside it. The analyzer artifact lets reviewers inspect the retained modules. Measurement and browser fixtures
| React workload | Features in the earlier v6 chunk that the route can omit |
|---|---|
| Read-only book list | Mutation cache and serial queues, infinite fetching, polling, selection, placeholder data, optimistic fetch, query Error Boundary handling, and bulk cache operations. |
| Paginated bookmarks | Polling, selection, placeholder data, optimistic fetch, query Error Boundary handling, serial queues, and unused bulk operations. The save action still needs mutations. |
| Selection, serial saves and invalidation | Infinite fetching, polling, optimistic fetch, query Error Boundary handling, and bulk reads, writes, cancellation and reset. Invalidation and refetch stay. |
| Polling | Mutation cache, serial queues, selection, placeholder data, and bulk operations. This screen uses both Suspense and pagination. |
Preview checks three Brotli budgets. Importing the full React API costs 13,365 B, up 662 B from v6, so its limit increases by 365 B to exactly 13,365 B. The minimal reader uses 5,875 B. The new paginated bookmarks check covers reading, fetching the next page and saving a bookmark. Its limit is 8,196 B. The Size Limit action lists this as a new entry. Measuring the corresponding imports on query-v6 locally gives 9,725 B, a reduction of 1,529 B (15.72%). Preview size report
CI also bundles a read-only entry for each of the seven adapters. It checks that the core query client, cache, and observer survive, and that the mutation cache, serial queues, polling, selection, placeholder data, infinite observer, and multi-query observer do not. The comment shows the framework-specific costs of hydration and optimistic fetching. Cross-framework import checks
The public hydrate(client, { queries }, options) call still accepts query-only state, and hydrate can also restore paused mutations. React and Preact’s HydrationBoundary only restore queries, as does Solid’s query reader during SSR. Sending those three paths through the general function pulled in mutation, mutationCache, and serialScope in production builds. The adapters now call the query restoration function directly. CI builds both React and Preact with and without the boundary to verify that hydration comes in only where needed and mutation restoration stays out. Query hydration · PR bundle measurements
Lazy routes and independent deployments#
The example opens on a read-only book list. A paginated bookmarks shelf loads with React.lazy when the reader opens it or scrolls it into view. The fixture measures the bytes needed to show the book list, the additional download when the shelf opens, and the total for a reader who visits both. Deferring the mutation cache and infinite fetching makes the initial book list smaller and the first bookmarks visit larger. Book list and lazy-loaded bookmarks
On an ad-funded storefront, the product list and its first ad slot often share the initial load. Viewable impressions directly affect our ad revenue. If a visitor scrolls past the slot before the ad renders, we can lose that impression. The fixture measures transferred bytes. Timing, viewability, and revenue would need to be measured on a production storefront.
Independently built microfrontends can each use a small subset of Query. The browser fixture compares two self-contained remotes with a deployment that shares a single Query chunk. It checks the actual URLs requested on the first and return visits. Microfrontend fixture
Release timing#
A major release is our opportunity to change method calls, result fields, and option shapes. I'd like us to consider the direction for v6 and, if it needs a longer transition, adopt it progressively in v7 or later. More imports take effort to learn. Named exports, typed factories, and versioned guidance through skills or TanStack Intent could make migration easier. I'd like small frontends to be able to keep TanStack Query, including its cache semantics, as their requirements grow. TanStack Intent
✅ 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. - 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).