Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/react-query-pluggable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@tanstack/query-core': minor
'@tanstack/react-query-pluggable': minor
---

Add an experimental ESM-only React Query adapter backed by `@tanstack/query-core`. Apps can import polling, selection, placeholder data, and serial mutation queues where they use them. Use `useQuery(query(options))` for a regular read and `useQuery(suspenseQuery(options))` to suspend on the same cache. Compose `infiniteQuery(options)` with the same hook and Suspense policy to read pages. For imperative fetching, import `fetchInfiniteQuery(client, options)`. Client operations are named functions with the client as their first argument, including `getQueryData(client, key)` and `invalidateQueries(client, filters)`.

Mutation hooks acquire a cache on first use. For direct access, import `getMutationCache` and call `getMutationCache(client)`. Clients configured with a custom cache return that instance.
100 changes: 100 additions & 0 deletions .github/workflows/react-query-bundle-size.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
name: React Query app bundle size

on:
pull_request:
paths:
- '.github/workflows/react-query-bundle-size.yml'
- 'integrations/react/bundle-size/**'
- 'packages/query-core/**'
- 'packages/react-query/**'
- 'packages/react-query-pluggable/**'
- 'scripts/getTsdownConfig.js'
- '.nvmrc'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'

concurrency:
group: ${{ github.workflow }}-${{ github.event.number }}
cancel-in-progress: true

permissions: {}

jobs:
measure:
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
report: ${{ steps.measure.outputs.report }}
analyzer_url: ${{ steps.analyzer.outputs.artifact-url }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3
- name: Check out the unmodified PR base
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.pull_request.base.sha }}
path: .bundle-base
persist-credentials: false
- name: Install and build the baseline adapter
working-directory: .bundle-base
run: |
pnpm --filter root --filter '@tanstack/react-query...' install --frozen-lockfile
pnpm --filter '@tanstack/react-query...' run build
- name: Build workspace dependencies
run: pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build
- name: Build and measure production apps
id: measure
env:
QUERY_BASE_CHECKOUT: ${{ github.workspace }}/.bundle-base
working-directory: integrations/react/bundle-size
run: |
pnpm run measure
cat dist/report.md >> "$GITHUB_STEP_SUMMARY"
jq -Rsr '"report=" + tojson' dist/report.md >> "$GITHUB_OUTPUT"
- name: Install Chromium
working-directory: integrations/react/bundle-size
run: pnpm run browser:install
- name: Exercise production apps in Chromium
working-directory: integrations/react/bundle-size
run: pnpm run test:browser
- name: Upload interactive bundle treemaps
id: analyzer
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: react-query-bundle-analyzer
path: integrations/react/bundle-size/dist/analyzer/
if-no-files-found: error
retention-days: 30
comment:
if: github.event.pull_request.head.repo.full_name == github.repository
needs: measure
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Update bundle size comment
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.number }}
REPORT: ${{ needs.measure.outputs.report }}
ANALYZER_URL: ${{ needs.measure.outputs.analyzer_url }}
run: |
comments="repos/$REPO/issues/$PR_NUMBER/comments"
marker='<!-- react-query-app-bundle-size -->'
id=$(gh api --paginate --slurp "$comments?per_page=100" |
jq -r --arg marker "$marker" '[.[][] | select(.user.login == "github-actions[bot]" and (.body | startswith($marker)))][0].id // empty')
endpoint="$comments"
method=POST
if [[ -n "$id" ]]; then
endpoint="repos/$REPO/issues/comments/$id"
method=PATCH
fi
jq -n --arg marker "$marker" --argjson report "$REPORT" --arg analyzer "$ANALYZER_URL" \
'{body: ($marker + "\n" + $report + "\n[Download the interactive bundle treemaps](" + $analyzer + ")")}' |
gh api --silent --method "$method" "$endpoint" --input -
51 changes: 51 additions & 0 deletions integrations/react/bundle-size/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# React Query app bundle size

This workspace builds four browser apps against each adapter’s public package entry point. The read-only app fetches a book list with `useQuery(options)` in v6 and `useQuery(query(options))` in the pluggable adapter. The paginated app uses the query, infinite-query and mutation option factories to fetch additional pages and save bookmarks in browser storage. The polling app refreshes regular and infinite queries, both with and without Suspense. The pluggable app calls `useQuery` with `query(options)`, `infiniteQuery(options)`, `suspenseQuery(options)` or `suspenseQuery(infiniteQuery(options))` for each subscriber. The browser test holds the first responses until both dedicated Suspense boundaries show their fallbacks, then checks the resolved data and subsequent refetches. The options app keeps the previous page while fetching, selects the displayed titles, saves bookmarks in a serial scope, and invalidates the bookmark list. Each app uses the default client. The original adapter accepts a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper.

CI builds the original adapter and its dependencies from the PR's base commit. The experimental `@tanstack/react-query-pluggable` adapter, its `@tanstack/query-core` dependency, the app code, the bundler and both React packages come from the PR head. The report records both commit IDs.

## What the PR comment measures

The opening table compares the gzipped Query runtime for each workload. It shows both package sizes in bytes and the signed change in bytes and percent relative to v6. Expand either detail table to see the absolute minified, gzip and Brotli sizes.

1. **Query runtime used by the app.** Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the adapter’s retained modules into one ESM chunk, including all retained `@tanstack/query-core` modules from the same checkout as that adapter. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark directly measures the minified Query chunk, including its ESM import and export bindings. Its gzip and Brotli sizes describe compressing this chunk on its own. Percentages use the original adapter’s isolated chunk for that workload and encoding.
2. **Whole production app.** Vite builds the deployable application with its ordinary chunk layout, including React, React DOM, the app and the adapter. Each percentage uses the original adapter’s full app for that workload and encoding. Compressing these complete chunks accounts for compression shared between the app and its dependencies.

Both tables show the emitted JS byte length, gzip at level 9 and Brotli at quality 11. The benchmark compresses each emitted JS chunk independently and sums the lengths. HTML, source maps and analysis reports are excluded.

The pluggable options app calls `invalidateQueries(client, { queryKey: ['bookmarks'] })`. Every named client operation takes the client first. The benchmark checks retained exports to verify that importing `QueryClient` leaves out `fetchQuery`, `setQueryData` and bulk operations, and that each named operation is available when imported.

For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the whole production app and imports only React peer entry points. Feature checks cover modules in both the pluggable adapter and its shared core. Both the read-only and polling apps construct a `QueryClient` and use queries. The pluggable build must retain the query cache and observer and exclude the mutation cache, mutation and mutation observer. Both bookmark apps call `useMutation` and must retain all three mutation modules. The read-only app excludes the Suspense builder and policy. The polling app retains both. Pagination and polling retain the infinite query builder and observer. All four hook-driven apps exclude the imperative `fetchInfiniteQuery` implementation. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations.

The PR comment links to the workflow artifact containing an interactive HTML bundle analyzer for each package and workload. Open `dist/analyzer/<workload>/<adapter>.html` locally after running the benchmark. Select the `query-runtime` chunk to explore its constituent sources. The treemap shows module contributions from source maps. The tables use actual compressed chunk bytes.

## Run locally

For a comparison within the current checkout, run from the repository root after installing workspace dependencies:

```sh
pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build
pnpm --filter @tanstack/query-integration-react-bundle-size run measure
```

To reproduce the CI comparison, use a clean worktree of the base commit. Replace `BASE_SHA` with the base commit from the report.

```sh
git worktree add --detach ../query-bundle-base BASE_SHA
pnpm --dir ../query-bundle-base --filter root --filter '@tanstack/react-query...' install --frozen-lockfile
pnpm --dir ../query-bundle-base --filter '@tanstack/react-query...' run build
QUERY_BASE_CHECKOUT="$PWD/../query-bundle-base" pnpm --filter @tanstack/query-integration-react-bundle-size run measure
```

Read the summary and detailed tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist/<workload>/<adapter>` to try the built app.

Run the eight production app scenarios in Chromium after measuring:

```sh
cd integrations/react/bundle-size
pnpm exec playwright install chromium
pnpm test:browser
pnpm test:browser:ui
```

The last command starts Vitest in watch mode with a browser UI for inspecting and rerunning each adapter’s scenarios.
19 changes: 19 additions & 0 deletions integrations/react/bundle-size/analyze.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import path from 'node:path'
import { visualizer } from 'rollup-plugin-visualizer'

export function adapterTreemap(screen, packageName) {
const name = packageName.split('/')[1]
return visualizer({
filename: path.join(
import.meta.dirname,
'dist/analyzer',
screen,
name + '.html',
),
title: `${packageName} · ${screen}`,
template: 'treemap',
sourcemap: true,
// Make source names comparable across the PR base and head checkouts.
projectRoot: /^.*\/(?=(?:packages|integrations)\/)/,
})
}
136 changes: 136 additions & 0 deletions integrations/react/bundle-size/browser/apps.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { afterEach, describe, expect, it } from 'vitest'
import { commands } from 'vitest/browser'

const adapters = ['react-query', 'react-query-pluggable']

function mountApp(scenario, adapter) {
const frame = document.createElement('iframe')
frame.title = adapter
frame.src = `/${scenario}/${adapter}/index.html`
document.body.append(frame)
return frame
}

async function openApp(scenario, adapter) {
const frame = mountApp(scenario, adapter)
await expect
.poll(() => frame.contentDocument?.querySelector('li')?.textContent)
.toContain('Middlemarch')
return frame.contentDocument
}

afterEach(() => {
document.querySelector('iframe')?.remove()
localStorage.removeItem('bookmark')
localStorage.removeItem('bookmarks')
})

describe.each(adapters)('@tanstack/%s', (adapter) => {
it('renders a fetched reading list', async () => {
const app = await openApp('query', adapter)
expect(
Array.from(app.querySelectorAll('li'), (row) => row.textContent),
).toEqual(['Middlemarch', 'Persuasion'])
})

it('loads the next page and saves a bookmark', async () => {
const app = await openApp('paginated', adapter)
const more = Array.from(app.querySelectorAll('button')).find(
(button) => button.textContent === 'Load more',
)
more.click()
await expect.poll(() => app.querySelectorAll('li').length).toBe(4)
const third = app.querySelectorAll('li')[2]
expect(third.textContent).toContain('Villette')
third.querySelector('button').click()
await expect
.poll(() => app.body.textContent)
.toContain('Bookmarked: Villette')
expect(localStorage.getItem('bookmark')).toBe('Villette')
})

it('retains the previous selection, queues bookmarks and refreshes the cache', async () => {
const app = await openApp('options', adapter)
const view = app.defaultView
const originalFetch = view.fetch.bind(view)
const gate = Promise.withResolvers()
view.fetch = async (...args) => {
if (String(args[0]).endsWith('books-2.json')) await gate.promise
return originalFetch(...args)
}
const button = (label) =>
Array.from(app.querySelectorAll('button')).find(
(item) => item.textContent === label,
)
try {
button('Next page').click()
await expect
.poll(() => app.querySelector('[role="status"]')?.textContent)
.toBe('Showing the previous page')
expect(app.querySelector('ul').textContent).toContain('Middlemarch')
} finally {
gate.resolve()
view.fetch = originalFetch
}
await expect
.poll(() => app.querySelector('ul').textContent)
.toContain('Villette')
button('Bookmark this page').click()
await expect
.poll(() => app.body.textContent)
.toContain('Bookmarks: Villette, North and South')
expect(
Array.from(app.querySelectorAll('ol li'), (item) => item.textContent),
).toEqual([
'Saving Villette',
'Saved Villette',
'Saving North and South',
'Saved North and South',
])
})

it('periodically refetches regular, infinite and suspense queries', async () => {
await commands.holdPollingBooks(adapter)
const frame = mountApp('polling', adapter)
try {
await commands.waitForPollingRequest(adapter)
await expect
.poll(() =>
Array.from(
frame.contentDocument.querySelectorAll('[role="status"]'),
(element) => element.textContent,
),
)
.toEqual(['Loading suspense query…', 'Loading suspense pages…'])
} finally {
await commands.releasePollingBooks(adapter)
}
const app = frame.contentDocument
await expect
.poll(() =>
Array.from(app.querySelectorAll('li'), (item) =>
item.textContent.includes('Middlemarch'),
),
)
.toEqual([true, true, true, true])
const timestamps = () =>
Array.from(app.querySelectorAll('time'), (time) => time.dateTime)
await expect.poll(() => timestamps().length).toBe(4)
// Two successive refreshes for every hook distinguish interval polling from a mount refetch.
for (let refresh = 0; refresh < 2; refresh++) {
const previous = timestamps()
await expect
.poll(
() => {
const current = timestamps()
return (
current.length === 4 &&
current.every((value, index) => value > previous[index])
)
},
{ timeout: 4000 },
)
.toBe(true)
}
})
})
12 changes: 12 additions & 0 deletions integrations/react/bundle-size/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Reading list</title>
</head>
<body>
<main id="root"></main>
<script type="module" src="./src/main.jsx"></script>
</body>
</html>
Loading
Loading