Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Tanstack Query Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-tanstack-query-knowledge-patch)
---
name: tanstack-query-knowledge-patch
description: TanStack Query
version: "5.101.4"
license: MIT
metadata:
author: Nevaberry
---
# TanStack Query Knowledge Patch
Load this skill when migrating TanStack Query APIs or working with query types,
persistence, cancellation, streaming, hydration, and observer behavior.
Use the topic references for complete guidance, examples, and release attribution.
## Reference index
| Reference | Topics |
| --- | --- |
| [API migrations and types](references/api-migrations-and-types.md) | Type parameters, query filters, inference, mutation context, prefetch options, activity counts, adapter dependencies |
| [Cache, cancellation, and tooling](references/cache-cancellation-and-tooling.md) | Persisters, rollback, abort signals, replacement fetches, cache removal, lint rules, notification scheduler |
| [Runtime and observers](references/runtime-and-observers.md) | Environment detection, timers, retries, staleness, pagination, mutation execution, React rendering and combined results |
| [Streaming and hydration](references/streaming-and-hydration.md) | Stream migration, empty streams, cancellation writes, hydration, dehydration, render-prefetch promises |
## Breaking changes and deprecations
### Streamed-query options
In `experimental_streamedQuery`, use `streamFn` instead of the former inner
`queryFn` option. Replace `maxChunks` with a custom `reducer` and supply an explicit
`initialValue`. Use `refetchMode: 'replace'` to keep the cached result visible
during a refetch and swap it out when the new stream finishes.
```ts
import { experimental_streamedQuery as streamedQuery } from '@tanstack/query-core'
const queryFn = streamedQuery({
streamFn: async function* () {
yield 'ready'
},
initialValue: [] as string[],
reducer: (chunks, chunk) => [...chunks, chunk].slice(-10),
refetchMode: 'replace',
})
```
### Deprecated and renamed exports
- The direct `isServer` export is deprecated in favor of `environmentManager.isServer()`.
- Update imports of `defaultshouldRedactErrors` to `defaultShouldRedactErrors`.
- `createSyncStoragePersister` is deprecated.
- Remove `NoInfer` imports from `@tanstack/query-core`; use the global type available
in TypeScript 5.4 and later. In generic code, `NoInfer<X[K]>` stays assignable to `X[K]`.
### Persister restoration
Use the returned `persisterFn` for the query's `persister` option.
`restoreQueries` replaces `persisterRestoreAll` and accepts filters to restore
selected queries. The cache reference includes the complete setup example.
### Infinite-query type contracts
`InfiniteQueryObserverOptions` dropped `TQueryData`. Remove that argument from
explicit annotations so the query key and page parameter occupy the correct positions.
From 5.108.1, the types for `queryClient.infiniteQuery`, the deprecated infinite-query
client methods, and React's `usePrefetchInfiniteQuery` require `getNextPageParam`,
even when `pages` is omitted. Reuse options from `useInfiniteQuery` so a stale refetch
can compute parameters for all cached pages.
### Prefetch and activity-count filters
React prefetch hooks reject `skipToken` as a `queryFn`. For conditional prefetching,
mount the component that calls the hook once its inputs are available.
- Omit `fetchStatus` from filters for `queryClient.isFetching`, React's `useIsFetching`,
and Angular's `injectIsFetching`; they count only fetching queries.
- Omit `status` from filters for `queryClient.isMutating`, React's `useIsMutating`,
and Angular's `injectIsMutating`; they count only pending mutations.
## Mutation context and execution
Mutation functions and lifecycle callbacks receive a final context argument with
access to the `QueryClient`. `onSuccess` takes the inferred `onMutate` result type
without adding `undefined`.
```ts
import { useMutation } from '@tanstack/react-query'
useMutation({
mutationFn: async (id: string) => ({ id }),
onMutate: (id) => ({ key: ['todo', id] }),
onSuccess: (todo, _id, { key }, { client }) => {
client.setQueryData(key, todo)
},
})
```
Enable `@tanstack/query/mutation-property-order` to keep `onMutate` ahead of callbacks
that consume its result, so TypeScript can infer the result type.
When `MutationCache` has no global `onMutate`, a mutation's `onMutate` starts
synchronously: a synchronous optimistic cache write runs before `mutate` returns.
A queued mutation can start when its turn in the scope arrives in an unfocused window.
## Query keys and inference
Query filters support typed keys. A filter's `predicate` receives a general `Query`;
narrow its key in the predicate when accessing key-specific fields.
`QueryFilters` accepts tuple prefixes, including readonly prefixes of key unions
whose members have different lengths.
A typed `persister` can supply inference for `TQueryFnData`, including when the query
function declares a context parameter. Its key type is wrapped in `NoInfer` to keep
a specific query key from widening to the registered `Register.queryKey` type.
TypeScript preserves discriminated union narrowing inside `queryClient.setQueryData` updaters.
Partial query-key matching distinguishes arrays from plain objects at the same
position. Use a shorter prefix such as `['todos']` to match either shape in the next position.
## Runtime configuration
Pass a `() => boolean` callback to `environmentManager.setIsServer` to override server
detection globally. Restore the default with a callback returning the original `isServer` value.
Use `timeoutManager.setTimeoutProvider(provider)` to replace Query's timers. The provider
supplies `setTimeout`, `clearTimeout`, `setInterval`, and `clearInterval`.
Pass `defaultScheduler` to `notifyManager.setScheduler(defaultScheduler)` to restore
the notification scheduler after an override.
## Retries, staleness, and initial data
`retryOnMount` accepts a `(query) => boolean` callback, allowing a decision based on
the current error. In React, mount retries are available when `throwOnError` is a function.
A query with a falsy error value can retry on mount when its `throwOnError` callback returns `false`.
A failed refetch makes existing data stale even while it remains available in the cache.
Mounting an observer with `initialData` can seed a cached query that has no data.
`staleTime: 'static'` makes a query static only once it has data; without data, it can
fetch after reset, invalidation, or an explicit refetch.
## Cancellation and cache lifecycle
Cancellation with rollback reverts state synchronously, incorporates manual cache
writes made during the fetch, and preserves defined data when rollback state has no data.
Infinite-query functions receive the original abort reason in `signal.reason`.
A paused initial fetch is canceled when its last observer unsubscribes.
When invalidation cancels and replaces an in-flight fetch, callers already awaiting
that query follow the replacement fetch, including across repeated invalidations.
Canceling a paused `queryClient.refetchQueries` refetch started with `throwOnError: true`
is handled without an unhandled `CancelledError`.
`queryCache.remove(query)` ignores instances that have already left the cache, preserving
a replacement with the same query hash. Removing an entry clears its garbage collection
timer; later fetch or observer cleanup leaves that removed entry without a timer.
## Streaming and hydration
A fresh `experimental_streamedQuery` stream with no chunks resolves to `initialValue`.
Reset-mode refetches preserve the error state when the query has `initialData`.
Read `context.signal` inside `streamFn` to opt into signal-based cancellation.
From 5.105.2, canceling a streamed query blocks further stream writes to the query cache
and prevents a delayed stream from starting even when `streamFn` leaves the abort signal unread.
Hydration skips an incoming query promise when the cached query is already fetching;
the existing fetch continues. Hydrating a query whose promise has already resolved avoids
a transient pending or fetching state. Streamed queries resolved before hydration retain `dataUpdatedAt`,
and server-rendered infinite queries retain their pagination behavior after hydration.
If a paused mutation can run when its async `onMutate` resolves, `isPaused` clears as
the request starts. Default dehydration skips that in-flight mutation, avoiding a second execution on resume.
With `experimental_prefetchInRender`, the result's `promise` rejects on a fetch error
only when there is no data. Reading `promise` also tracks changes to `data`.
## React observers and rendering
- With `subscribed: false`, React Query reflects cached fetch state without reporting
an optimistic fetch on mount.
- `useSuspenseQueries` defers `combine` until queries can render without suspending.
- `useMutationState` and `useIsMutating` recompute when their filters or query client
change, independently of mutation cache updates. Changing `useMutationState`'s `select`
also triggers recomputation. Both hooks reflect the cleared cache after `queryClient.clear()`.
- `placeholderData: keepPreviousData` retains a memoized `undefined` from `select`,
preventing disabled or still-loading queries from cycling between `pending` and `success` for that result.
- After `setQueries`, `QueriesObserver` combines results from the new list even if a
previous query updated just before the switch. This also applies to `useQueries` with `combine`.
- A `placeholderData` callback or `select` producing a fresh result every render no
longer triggers a render loop on its own.
## Infinite-query pages and lint checks
After lowering `maxPages`, fetching the next or previous page trims cached pages to
the new limit. A refetch uses `pageParam: null` for the first page when cached
`pageParams[0]` is `null`, even if `initialPageParam` differs.
`infiniteQueryOptions` selects the overload allowing absent initial data when
`initialData` may be `undefined`.
`@tanstack/query/no-rest-destructuring` also detects query-result object spreads such
as `{ ...result }`. Read the fields you need directly to preserve selective property tracking.
`@tanstack/query/no-void-query-fn` flags query functions that return no value.