Skip to content
Open
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
19 changes: 19 additions & 0 deletions .changeset/treeshakable-query.md
Original file line number Diff line number Diff line change
@@ -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.
113 changes: 113 additions & 0 deletions .github/workflows/query-bundle-size.yml
Original file line number Diff line number Diff line change
@@ -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='<!-- tanstack-query-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 -
11 changes: 9 additions & 2 deletions .size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
}
]
4 changes: 4 additions & 0 deletions docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
},
Expand Down
17 changes: 11 additions & 6 deletions docs/eslint/prefer-query-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -81,7 +86,7 @@ function todoOptions(id) {

function Component({ id }) {
const queryClient = useQueryClient()
return queryClient.getQueryData(['todo', id])
return getQueryData(queryClient, ['todo', id])
}
```

Expand All @@ -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] })
}
```

Expand All @@ -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)
}
```

Expand All @@ -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 })
}
```

Expand Down
20 changes: 13 additions & 7 deletions docs/framework/angular/guides/infinite-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
24 changes: 17 additions & 7 deletions docs/framework/angular/guides/polling.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,32 @@ 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
}))
```

[//]: # 'Example1'
[//]: # '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
},
}),
}
})
```
Expand All @@ -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,
}))
```
Expand All @@ -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()
Expand All @@ -58,10 +66,10 @@ injectQuery(() => {
return {
queryKey: ['prices', tokenAddress],
queryFn: () => fetchPrice(tokenAddress),
refetchInterval: () => {
refetchInterval: refetchInterval(() => {
if (!tokenAddress || isPaused) return false
return 15 * 1000
},
}),
}
})
```
Expand All @@ -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',
}))
```
Expand Down
23 changes: 16 additions & 7 deletions docs/framework/angular/guides/query-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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'
Loading
Loading