diff --git a/.changeset/treeshakable-query.md b/.changeset/treeshakable-query.md new file mode 100644 index 00000000000..63d6daddc8f --- /dev/null +++ b/.changeset/treeshakable-query.md @@ -0,0 +1,19 @@ +--- +'@tanstack/query-core': major +'@tanstack/react-query': major +'@tanstack/preact-query': major +'@tanstack/angular-query': major +'@tanstack/solid-query': major +'@tanstack/svelte-query': major +'@tanstack/vue-query': major +'@tanstack/lit-query': major +'@tanstack/query-broadcast-client-experimental': patch +'@tanstack/query-persist-client-core': patch +'@tanstack/query-devtools': patch +--- + +Make the ESM query core and its framework adapters treeshakable. Import client operations such as `query(client, options)`, `invalidateQueries(client, filters)`, and `getMutationCache(client)` from the adapter. A read-only client no longer needs to construct a mutation cache. + +In React and Preact, pass `queryOptions`, `suspenseQueryOptions`, `infiniteQueryOptions`, or `suspenseInfiniteQueryOptions` to `useQuery`. Import result checks such as `isSuccess(result)` to narrow data or errors. Use `useQueries` and `useSuspenseQueries` for a variable number of queries. + +Import `select`, `placeholderData`, `refetchInterval`, and `serialScope` where those features are used. Write `select: select((post) => post.title)` to project the observer's data while keeping the full post in the cache. Structural sharing remains enabled by default. Ordinary React and Preact queries can opt into boundaries with `throwOnError: [throwOnError, true]` or a predicate in the second position. diff --git a/.github/workflows/query-bundle-size.yml b/.github/workflows/query-bundle-size.yml new file mode 100644 index 00000000000..a8fd2f651cd --- /dev/null +++ b/.github/workflows/query-bundle-size.yml @@ -0,0 +1,113 @@ +name: TanStack Query bundle size + +on: + pull_request: + paths: + - '.github/workflows/query-bundle-size.yml' + - 'integrations/react/bundle-size/**' + - 'packages/query-core/**' + - 'packages/*-query/**' + - 'integrations/query/treeshaking/**' + - '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 v6 comparison baseline + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + # The v6 fixtures use the API from before the treeshakable changes. + ref: dc33f10cc5d7334a3b473fdf576b5d2aeb57ef4b + path: .cache/query-bundle-base + persist-credentials: false + - name: Install and build the baseline adapter + working-directory: .cache/query-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-treeshaking^...' run build + - name: Verify read-only imports across framework adapters + working-directory: integrations/query/treeshaking + run: | + pnpm run test:types + node check.ts > "$RUNNER_TEMP/query-readers.md" + - name: Type-check the benchmark and both adapters' screens + working-directory: integrations/react/bundle-size + run: | + pnpm run test:types + pnpm run check:baseline + - name: Build and measure production apps + id: measure + env: + QUERY_BASE_CHECKOUT: ${{ github.workspace }}/.cache/query-bundle-base + working-directory: integrations/react/bundle-size + run: | + pnpm run measure + echo >> dist/report.md + cat "$RUNNER_TEMP/query-readers.md" >> dist/report.md + 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='' + 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 - diff --git a/.size-limit.json b/.size-limit.json index c988ea32153..29589775464 100644 --- a/.size-limit.json +++ b/.size-limit.json @@ -2,14 +2,21 @@ { "name": "react full", "path": "packages/react-query/build/index.js", - "limit": "13.00 kB", + "limit": "13365 B", "ignore": ["react", "react-dom"] }, { "name": "react minimal", "path": "packages/react-query/build/index.js", "limit": "9.99 kB", - "import": "{ useQuery, QueryClient, QueryClientProvider }", + "import": "{ queryOptions, useQuery, QueryClient, QueryClientProvider }", + "ignore": ["react", "react-dom"] + }, + { + "name": "react paginated bookmarks", + "path": "packages/react-query/build/index.js", + "limit": "8196 B", + "import": "{ QueryClient, QueryClientProvider, queryOptions, useQuery, infiniteQueryOptions, isError, isFetching, isPending, mutationOptions, useMutation }", "ignore": ["react", "react-dom"] } ] diff --git a/docs/config.json b/docs/config.json index 065b61cc206..77553bbfe3d 100644 --- a/docs/config.json +++ b/docs/config.json @@ -386,6 +386,10 @@ { "label": "Migrating to v5", "to": "framework/react/guides/migrating-to-v5" + }, + { + "label": "Migrating to v6", + "to": "framework/react/guides/migrating-to-v6" } ] }, diff --git a/docs/eslint/prefer-query-options.md b/docs/eslint/prefer-query-options.md index 3228774bf7d..16b1596edb8 100644 --- a/docs/eslint/prefer-query-options.md +++ b/docs/eslint/prefer-query-options.md @@ -61,11 +61,16 @@ function getFooOptions(id) { } function useFooQuery(id) { - return useQuery({ ...getFooOptions(id), select: (data) => data.foo }) + return useQuery( + queryOptions({ + ...getFooOptions(id), + select: select((data) => data.foo), + }), + ) } ``` -The rule also enforces reusing `queryKey` from a `queryOptions` result instead of typing it manually in `QueryClient` methods or filters. +The rule also enforces reusing `queryKey` from a `queryOptions` result instead of typing it manually in client-first operations or filters. It recognizes named imports and aliases from TanStack Query. Examples of **incorrect** `queryKey` references for this rule: @@ -81,7 +86,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.getQueryData(['todo', id]) + return getQueryData(queryClient, ['todo', id]) } ``` @@ -97,7 +102,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.invalidateQueries({ queryKey: ['todo', id] }) + return invalidateQueries(queryClient, { queryKey: ['todo', id] }) } ``` @@ -115,7 +120,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.getQueryData(todoOptions(id).queryKey) + return getQueryData(queryClient, todoOptions(id).queryKey) } ``` @@ -131,7 +136,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.invalidateQueries({ queryKey: todoOptions(id).queryKey }) + return invalidateQueries(queryClient, { queryKey: todoOptions(id).queryKey }) } ``` diff --git a/docs/framework/angular/guides/infinite-queries.md b/docs/framework/angular/guides/infinite-queries.md index b912fb41470..9ec9abfa1ad 100644 --- a/docs/framework/angular/guides/infinite-queries.md +++ b/docs/framework/angular/guides/infinite-queries.md @@ -112,14 +112,20 @@ projectsQuery = injectInfiniteQuery(() => ({ [//]: # 'Example4' ```ts -projectsQuery = injectInfiniteQuery(() => ({ - queryKey: ['projects'], - queryFn: fetchProjects, - select: (data) => ({ - pages: [...data.pages].reverse(), - pageParams: [...data.pageParams].reverse(), +import { infiniteQueryOptions, select } from '@tanstack/angular-query' + +projectsQuery = injectInfiniteQuery(() => + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextCursor, + select: select((data) => ({ + pages: [...data.pages].reverse(), + pageParams: [...data.pageParams].reverse(), + })), }), -})) +) ``` [//]: # 'Example4' diff --git a/docs/framework/angular/guides/polling.md b/docs/framework/angular/guides/polling.md index 38e9b8a0b11..9fa041d3444 100644 --- a/docs/framework/angular/guides/polling.md +++ b/docs/framework/angular/guides/polling.md @@ -8,10 +8,12 @@ replace: { '@tanstack/react-query': '@tanstack/angular-query' } [//]: # 'Example1' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => ({ queryKey: ['prices'], queryFn: fetchPrices, - refetchInterval: 5 * 1000, // every 5 seconds + refetchInterval: refetchInterval(5 * 1000), // every 5 seconds })) ``` @@ -19,17 +21,19 @@ injectQuery(() => ({ [//]: # 'Example2' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => { const jobId = this.jobId() return { queryKey: ['job', jobId], queryFn: () => fetchJobStatus(jobId), - refetchInterval: (query) => { + refetchInterval: refetchInterval((query) => { // Stop polling once the job finishes if (query.state.data?.status === 'complete') return false return 2 * 1000 - }, + }), } }) ``` @@ -38,10 +42,12 @@ injectQuery(() => { [//]: # 'Example3' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => ({ queryKey: ['portfolio'], queryFn: fetchPortfolio, - refetchInterval: 30 * 1000, + refetchInterval: refetchInterval(30 * 1000), refetchIntervalInBackground: true, })) ``` @@ -50,6 +56,8 @@ injectQuery(() => ({ [//]: # 'Example4' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => { // Read signals here so the query reacts when they change const tokenAddress = this.tokenAddress() @@ -58,10 +66,10 @@ injectQuery(() => { return { queryKey: ['prices', tokenAddress], queryFn: () => fetchPrice(tokenAddress), - refetchInterval: () => { + refetchInterval: refetchInterval(() => { if (!tokenAddress || isPaused) return false return 15 * 1000 - }, + }), } }) ``` @@ -70,10 +78,12 @@ injectQuery(() => { [//]: # 'Example5' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => ({ queryKey: ['chainStatus'], queryFn: fetchChainStatus, - refetchInterval: 10 * 1000, + refetchInterval: refetchInterval(10 * 1000), networkMode: 'always', })) ``` diff --git a/docs/framework/angular/guides/query-options.md b/docs/framework/angular/guides/query-options.md index 691b52ec4fd..e833501ea6f 100644 --- a/docs/framework/angular/guides/query-options.md +++ b/docs/framework/angular/guides/query-options.md @@ -7,7 +7,12 @@ ref: docs/framework/react/guides/query-options.md [//]: # 'Example1' ```ts -import { noop, queryOptions } from '@tanstack/angular-query' +import { + noop, + query, + queryOptions, + setQueryData, +} from '@tanstack/angular-query' @Injectable({ providedIn: 'root', @@ -38,21 +43,25 @@ queries = inject(QueriesService) postQuery = injectQuery(() => this.queries.post(this.postId())) -void queryClient.query(this.queries.post(23)).catch(noop) -queryClient.setQueryData(this.queries.post(42).queryKey, newPost) +void query(queryClient, this.queries.post(23)).catch(noop) +setQueryData(queryClient, this.queries.post(42).queryKey, newPost) ``` [//]: # 'Example1' [//]: # 'Example2' ```ts +import { queryOptions, select } from '@tanstack/angular-query' + // Type inference still works, so postQuery.data will be the return type of select instead of queryFn queries = inject(QueriesService) -postQuery = injectQuery(() => ({ - ...this.queries.post(1), - select: (data) => data.title, -})) +postQuery = injectQuery(() => + queryOptions({ + ...this.queries.post(1), + select: select((data) => data.title), + }), +) ``` [//]: # 'Example2' diff --git a/docs/framework/angular/typescript.md b/docs/framework/angular/typescript.md index ffacb78c1c1..7ba7502b8c4 100644 --- a/docs/framework/angular/typescript.md +++ b/docs/framework/angular/typescript.md @@ -37,17 +37,21 @@ class MyComponent { [//]: # 'TypeInference2' ```angular-ts +import { queryOptions, select } from '@tanstack/angular-query' + @Component({ // ... template: `@let data = query.data();`, // ^? data: string | undefined }) class MyComponent { - query = injectQuery(() => ({ - queryKey: ['test'], - queryFn: () => Promise.resolve(5), - select: (data) => data.toString(), - })) + query = injectQuery(() => + queryOptions({ + queryKey: ['test'], + queryFn: () => Promise.resolve(5), + select: select((data) => data.toString()), + }), + ) } ``` diff --git a/docs/framework/preact/guides/infinite-queries.md b/docs/framework/preact/guides/infinite-queries.md index 77a6f6934f9..b502b2e54fb 100644 --- a/docs/framework/preact/guides/infinite-queries.md +++ b/docs/framework/preact/guides/infinite-queries.md @@ -8,7 +8,12 @@ replace: { 'react-query': 'preact-query', 'React': 'Preact' } [//]: # 'Example' ```tsx -import { useInfiniteQuery } from '@tanstack/preact-query' +import { + useQuery, + infiniteQueryOptions, + isFetching, + isFetchingNextPage, +} from '@tanstack/preact-query' function Projects() { const fetchProjects = async ({ pageParam }) => { @@ -16,28 +21,22 @@ function Projects() { return res.json() } - const { - data, - error, - fetchNextPage, - hasNextPage, - isFetching, - isFetchingNextPage, - status, - } = useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - }) + const infiniteQueryResult = useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + }), + ) - return status === 'pending' ? ( + return infiniteQueryResult.status === 'pending' ? (
Loading...
- ) : status === 'error' ? ( -Error: {error.message}
+ ) : infiniteQueryResult.status === 'error' ? ( +Error: {infiniteQueryResult.error.message}
) : ( <> - {data.pages.map((group, i) => ( + {infiniteQueryResult.data.pages.map((group, i) => ({project.name}
@@ -46,17 +45,24 @@ function Projects() { ))}Loading...
- ) : status === 'error' ? ( -Error: {error.message}
+ ) : infiniteQueryResult.status === 'error' ? ( +Error: {infiniteQueryResult.error.message}
) : ( <> - {data.pages.map((group, i) => ( + {infiniteQueryResult.data.pages.map((group, i) => ({project.name}
@@ -81,17 +80,24 @@ function Projects() { ))}{article.error.message}
+ return{project.name}
))}