}>.
+function PostTitle({ id }: { id: number }) {
+ const post = useQuery(suspenseQuery(postOptions(id)))
+ return
{post.data.title}
+}
+```
+
+The Suspense policy sends a failed query without cached data to the nearest error boundary.
+Passing `skipToken` skips the fetch and can yield undefined data. `useSuspenseQuery(options)`
+is a shorthand for `useQuery(suspenseQuery(options))`.
+
+### Paginated queries with the same hook
+
+Build the observer with `infiniteQuery`. Wrap those options in `suspenseQuery` when React
+should show a parent fallback while loading the first page. Both forms expose `fetchNextPage`,
+`hasNextPage`, and the cached `pages` and `pageParams`.
+
+```tsx
+import {
+ infiniteQuery,
+ suspenseQuery,
+ useQuery,
+} from '@tanstack/react-query-pluggable'
+
+const postPages = infiniteQuery({
+ queryKey: ['posts', 'pages'],
+ initialPageParam: 0,
+ queryFn: ({ pageParam }) => fetchPostPage(pageParam),
+ getNextPageParam: (lastPage) => lastPage.nextCursor,
+})
+
+function Posts() {
+ const result = useQuery(suspenseQuery(postPages))
+ return (
+ <>
+ {result.data.pages.map((page) => (
+
+ ))}
+
+ >
+ )
+}
+```
+
+Use `useQuery(postPages)` to handle the pending state inside the component. Outside React, import
+`fetchInfiniteQuery` to fetch and cache pages by calling `fetchInfiniteQuery(client, postPages)`.
+
+## Selecting and keeping data
+
+`select` maps the cached value for one observer. `placeholderData` supplies a temporary value for a pending query. Wrap a typed selector in `select(getTitle)`, or use the tuple form to infer an inline callback's argument from the query. For example, this hook keeps displaying the previous post title while the next post loads.
+
+```tsx
+import {
+ keepPreviousData,
+ placeholderData,
+ select,
+ useQuery,
+} from '@tanstack/react-query-pluggable'
+
+function usePostTitle(id: number) {
+ return useQuery({
+ queryKey: ['post', id],
+ queryFn: () => fetchPost(id), // Promise<{ title: string }>
+ select: [select, (post) => post.title],
+ placeholderData: placeholderData(keepPreviousData),
+ })
+}
+```
+
+## Client operations
+
+The `QueryClient` constructor creates the state shared by hooks, providers and imperative callers. All operations on that client are named functions. Pass the client first, followed by the arguments you would pass to the v6 method.
+
+```ts
+import {
+ fetchQuery,
+ fetchInfiniteQuery,
+ getQueryData,
+ invalidateQueries,
+ setQueryData,
+} from '@tanstack/react-query-pluggable'
+
+const order = await fetchQuery(client, orderOptions)
+const cached = getQueryData(client, orderOptions.queryKey)
+setQueryData(client, orderOptions.queryKey, updatedOrder)
+await fetchInfiniteQuery(client, orderPageOptions)
+await invalidateQueries(client, { queryKey: ['orders'] })
+```
+
+For example, `client.query(options)` becomes `fetchQuery(client, options)` and `client.clear()` becomes `clearQueryClient(client)`. The provider manages mounting for React users. Integrations that managed the v6 lifecycle directly can call `mountQueryClient(client)` and `unmountQueryClient(client)`. The same client-first convention applies to defaults, mutation resumption and bulk cache operations.
+
+Use `getQueryCache(client)` and `getMutationCache(client)` for direct cache access. Cache objects keep methods such as `.subscribe(listener)`, `.find(filters)`, and `.getAll()`. The stock `@tanstack/query-persist-client-core` subscription calls `client.getQueryCache()` and `client.getMutationCache()`. A custom persistence integration for this adapter must subscribe through the named accessors and use this adapter’s `hydrate` and `dehydrate`.
+
+## Mutations
+
+`useMutation`, `useMutationState`, and `useIsMutating` acquire the client's mutation cache on demand. `getMutationCache(client)` creates a default cache on first use or returns a cache supplied to the constructor. A query-only app can omit the mutation cache implementation.
+
+Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. The scope ID survives dehydration and hydration. The `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers preserve their TypeScript inference and share one JavaScript identity function.
diff --git a/packages/react-query-pluggable/oxlint.config.ts b/packages/react-query-pluggable/oxlint.config.ts
new file mode 100644
index 00000000000..91da02f7ef4
--- /dev/null
+++ b/packages/react-query-pluggable/oxlint.config.ts
@@ -0,0 +1,51 @@
+import pluginReact from '@eslint-react/eslint-plugin'
+import reactHooks from 'eslint-plugin-react-hooks'
+import { defineConfig } from 'oxlint'
+import rootConfig from './root.oxlint.config.ts'
+
+export default defineConfig({
+ extends: [rootConfig],
+ settings: rootConfig.settings,
+ jsPlugins: [
+ // 'react-hooks' is reserved for Oxlint's native plugin, which lacks the React Compiler rules
+ { name: 'react-hooks-js', specifier: 'eslint-plugin-react-hooks' },
+ '@eslint-react/eslint-plugin',
+ ],
+ rules: {
+ ...Object.fromEntries(
+ Object.entries(reactHooks.configs.flat.recommended.rules).map(
+ ([name, value]) => [
+ name.replace(/^react-hooks\//, 'react-hooks-js/'),
+ value,
+ ],
+ ),
+ ),
+ ...pluginReact.configs.recommended.rules,
+ 'react-hooks-js/exhaustive-deps': 'error',
+ 'react-hooks-js/unsupported-syntax': 'error',
+ 'react-hooks-js/incompatible-library': 'error',
+ '@eslint-react/no-context-provider': 'off', // We need to be React 18 compatible
+ '@eslint-react/no-use-context': 'off', // We need to be React 18 compatible
+ // Covered by 'eslint-plugin-react-hooks'
+ '@eslint-react/error-boundaries': 'off',
+ '@eslint-react/exhaustive-deps': 'off',
+ '@eslint-react/globals': 'off',
+ '@eslint-react/immutability': 'off',
+ '@eslint-react/purity': 'off',
+ '@eslint-react/refs': 'off',
+ '@eslint-react/rules-of-hooks': 'off',
+ '@eslint-react/set-state-in-effect': 'off',
+ '@eslint-react/set-state-in-render': 'off',
+ '@eslint-react/static-components': 'off',
+ '@eslint-react/unsupported-syntax': 'off',
+ '@eslint-react/use-memo': 'off',
+ },
+ overrides: [
+ {
+ files: ['**/__tests__/**'],
+ rules: {
+ 'typescript/no-unnecessary-condition': 'off',
+ },
+ },
+ ],
+})
diff --git a/packages/react-query-pluggable/package.json b/packages/react-query-pluggable/package.json
new file mode 100644
index 00000000000..e6a08663d84
--- /dev/null
+++ b/packages/react-query-pluggable/package.json
@@ -0,0 +1,84 @@
+{
+ "name": "@tanstack/react-query-pluggable",
+ "version": "5.108.4",
+ "description": "Experimental ESM React Query adapter with per-option features and tree-shakable cache operations",
+ "author": "tannerlinsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/TanStack/query.git",
+ "directory": "packages/react-query-pluggable"
+ },
+ "homepage": "https://tanstack.com/query",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "scripts": {
+ "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types",
+ "compile": "tsc --project tsconfig.json",
+ "test:oxlint": "oxlint ./src ./tests",
+ "test:types": "npm-run-all --serial test:types:*",
+ "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo",
+ "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo",
+ "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo",
+ "test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo",
+ "test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo",
+ "test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo",
+ "test:lib": "vitest run --typecheck src/__tests__ && node ../../scripts/test-react-query-compat.mjs",
+ "test:lib:dev": "vitest --watch src/__tests__",
+ "test:build": "publint --strict && attw --pack --profile esm-only",
+ "build": "tsdown --tsconfig tsconfig.prod.json"
+ },
+ "type": "module",
+ "types": "./build/index.d.ts",
+ "main": "./build/index.js",
+ "react-native": "src/index.ts",
+ "exports": {
+ ".": {
+ "@tanstack/custom-condition": "./src/index.ts",
+ "types": "./build/index.d.ts",
+ "default": "./build/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "files": [
+ "build",
+ "src",
+ "!src/__tests__"
+ ],
+ "dependencies": {
+ "@tanstack/query-core": "workspace:*"
+ },
+ "devDependencies": {
+ "@eslint-react/eslint-plugin": "catalog:",
+ "@testing-library/react": "catalog:",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "eslint-plugin-react-hooks": "catalog:",
+ "react": "catalog:",
+ "react-dom": "catalog:",
+ "typescript": "catalog:"
+ },
+ "peerDependencies": {
+ "@types/react": "^19",
+ "react": "^19"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ },
+ "nx": {
+ "targets": {
+ "test:lib": {
+ "inputs": [
+ "default",
+ "^production",
+ "reactQueryCompatibility"
+ ]
+ }
+ }
+ }
+}
diff --git a/packages/react-query-pluggable/root.oxlint.config.ts b/packages/react-query-pluggable/root.oxlint.config.ts
new file mode 120000
index 00000000000..56565c65534
--- /dev/null
+++ b/packages/react-query-pluggable/root.oxlint.config.ts
@@ -0,0 +1 @@
+../../oxlint.config.ts
\ No newline at end of file
diff --git a/packages/react-query-pluggable/root.tsdown.config.js b/packages/react-query-pluggable/root.tsdown.config.js
new file mode 120000
index 00000000000..a997d5d337c
--- /dev/null
+++ b/packages/react-query-pluggable/root.tsdown.config.js
@@ -0,0 +1 @@
+../../scripts/getTsdownConfig.js
\ No newline at end of file
diff --git a/packages/react-query-pluggable/src/HydrationBoundary.tsx b/packages/react-query-pluggable/src/HydrationBoundary.tsx
new file mode 100644
index 00000000000..cc55339b646
--- /dev/null
+++ b/packages/react-query-pluggable/src/HydrationBoundary.tsx
@@ -0,0 +1,137 @@
+'use client'
+import * as React from 'react'
+import { useQueryClient } from './QueryClientProvider'
+import { hydrateQueries } from './runtime/hydration'
+import { getQueryCache } from './runtime/queryClient'
+import type { DehydratedState, OmitKeyof } from '@tanstack/query-core'
+import type { HydrateOptions } from './runtime/hydration'
+import type { QueryClient } from './runtime/queryClient'
+
+/**
+ * The props accepted by `HydrationBoundary`.
+ */
+export interface HydrationBoundaryProps {
+ /**
+ * The state to hydrate. Pass the result of `dehydrate(queryClient)`.
+ */
+ state: DehydratedState
+ /**
+ * Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
+ */
+ options?: OmitKeyof & {
+ defaultOptions?: OmitKeyof<
+ Exclude,
+ 'mutations'
+ >
+ }
+ /**
+ * The components to render — always rendered unconditionally, not gated on hydration. New queries are
+ * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
+ * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
+ * lands.
+ */
+ children?: React.ReactNode
+ /**
+ * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
+ */
+ queryClient?: QueryClient
+}
+
+/**
+ * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
+ * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
+ * update timestamp.
+ *
+ * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
+ * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom
+ * `queryClient`, and the `children` to render.
+ * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
+ * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
+ * after commit.
+ * @example
+ * ```tsx
+ * import { HydrationBoundary } from '@tanstack/react-query-pluggable'
+ *
+ * function App() {
+ * return ...
+ * }
+ * ```
+ * @example
+ * Server-side prefetch handed off to the client via `dehydrate`:
+ * ```tsx
+ * import { HydrationBoundary, dehydrate, noop, fetchQuery } from '@tanstack/react-query-pluggable'
+ *
+ * async function ServerComponent() {
+ * const queryClient = getQueryClient()
+ *
+ * await fetchQuery(queryClient, {
+ * queryKey: ['posts'],
+ * queryFn: fetchPosts,
+ * })
+ * .catch(noop)
+ *
+ * return (
+ *
+ *
+ *
+ * )
+ * }
+ * ```
+ */
+export const HydrationBoundary = ({
+ children,
+ options = {},
+ state,
+ queryClient,
+}: HydrationBoundaryProps) => {
+ const client = useQueryClient(queryClient)
+
+ const optionsRef = React.useRef(options)
+ React.useEffect(() => {
+ optionsRef.current = options
+ })
+
+ // Hydrate new queries during render so children can read their data.
+ // Hydrate existing queries after commit so an aborted transition cannot update them.
+ const hydrationQueue: DehydratedState['queries'] | undefined =
+ React.useMemo(() => {
+ const queryCache = getQueryCache(client)
+
+ const newQueries: DehydratedState['queries'] = []
+ const existingQueries: DehydratedState['queries'] = []
+ for (const dehydratedQuery of state.queries) {
+ const existingQuery = queryCache.get(dehydratedQuery.queryHash)
+
+ if (!existingQuery) {
+ newQueries.push(dehydratedQuery)
+ continue
+ }
+
+ const hydrationIsNewer =
+ dehydratedQuery.state.dataUpdatedAt >
+ existingQuery.state.dataUpdatedAt ||
+ (dehydratedQuery.promise &&
+ existingQuery.state.status !== 'pending' &&
+ existingQuery.state.fetchStatus !== 'fetching' &&
+ dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt)
+
+ if (hydrationIsNewer) {
+ existingQueries.push(dehydratedQuery)
+ }
+ }
+
+ if (newQueries.length > 0) {
+ // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo
+ hydrateQueries(client, newQueries, optionsRef.current)
+ }
+ return existingQueries.length > 0 ? existingQueries : undefined
+ }, [client, state])
+
+ React.useEffect(() => {
+ if (hydrationQueue) {
+ hydrateQueries(client, hydrationQueue, optionsRef.current)
+ }
+ }, [client, hydrationQueue])
+
+ return children as React.ReactElement
+}
diff --git a/packages/react-query-pluggable/src/IsRestoringProvider.ts b/packages/react-query-pluggable/src/IsRestoringProvider.ts
new file mode 100644
index 00000000000..abb353406a6
--- /dev/null
+++ b/packages/react-query-pluggable/src/IsRestoringProvider.ts
@@ -0,0 +1,18 @@
+'use client'
+import * as React from 'react'
+
+const IsRestoringContext = React.createContext(false)
+
+/**
+ * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to
+ * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid
+ * race conditions between the restore and mounting queries.
+ * @returns `true` while a persisted client is being restored, `false` otherwise.
+ */
+export const useIsRestoring = () => React.useContext(IsRestoringContext)
+
+/**
+ * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently
+ * being restored, read by `useIsRestoring`.
+ */
+export const IsRestoringProvider = IsRestoringContext.Provider
diff --git a/packages/react-query-pluggable/src/QueryClientProvider.tsx b/packages/react-query-pluggable/src/QueryClientProvider.tsx
new file mode 100644
index 00000000000..3e3f822d84d
--- /dev/null
+++ b/packages/react-query-pluggable/src/QueryClientProvider.tsx
@@ -0,0 +1,85 @@
+'use client'
+import * as React from 'react'
+import { mountQueryClient, unmountQueryClient } from './runtime/queryClient'
+import type { QueryClient } from './runtime/queryClient'
+
+/**
+ * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
+ */
+export const QueryClientContext = React.createContext(
+ undefined,
+)
+
+/**
+ * The `useQueryClient` hook returns the current `QueryClient` instance.
+ * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
+ * be used.
+ * @returns The current `QueryClient` instance.
+ * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the
+ * component tree.
+ */
+export const useQueryClient = (queryClient?: QueryClient) => {
+ const client = React.useContext(QueryClientContext)
+
+ if (queryClient) {
+ return queryClient
+ }
+
+ if (!client) {
+ throw new Error('No QueryClient set, use QueryClientProvider to set one')
+ }
+
+ return client
+}
+
+/**
+ * The props accepted by `QueryClientProvider`.
+ */
+export type QueryClientProviderProps = {
+ /**
+ * **Required**
+ *
+ * The `QueryClient` instance to provide.
+ */
+ client: QueryClient
+ /**
+ * The components that get access to the provided `QueryClient`.
+ */
+ children?: React.ReactNode
+}
+
+/**
+ * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
+ * calls `mountQueryClient(client)`/`unmountQueryClient(client)` as this component mounts/unmounts, which subscribes the client to
+ * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
+ * comes back online).
+ * @param props - The `client` to provide, and the `children` that get access to it.
+ * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
+ * @example
+ * ```tsx
+ * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-pluggable'
+ *
+ * const queryClient = new QueryClient()
+ *
+ * function App() {
+ * return ...
+ * }
+ * ```
+ */
+export const QueryClientProvider = ({
+ client,
+ children,
+}: QueryClientProviderProps): React.JSX.Element => {
+ React.useEffect(() => {
+ mountQueryClient(client)
+ return () => {
+ unmountQueryClient(client)
+ }
+ }, [client])
+
+ return (
+
+ {children}
+
+ )
+}
diff --git a/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx
new file mode 100644
index 00000000000..a8835dea36b
--- /dev/null
+++ b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx
@@ -0,0 +1,169 @@
+'use client'
+import * as React from 'react'
+
+// CONTEXT
+
+/**
+ * Resets any query errors within the boundary, so queries know they can try again.
+ */
+export type QueryErrorResetFunction = () => void
+
+/**
+ * Returns whether the boundary has been reset and not yet cleared.
+ */
+export type QueryErrorIsResetFunction = () => boolean
+
+/**
+ * Clears the reset state, so queries know not to try again until the boundary is reset again.
+ */
+export type QueryErrorClearResetFunction = () => void
+
+/**
+ * The value a `QueryErrorResetBoundary` shares through context, used to reset query errors within
+ * it and to check whether a reset was requested.
+ */
+export interface QueryErrorResetBoundaryValue {
+ /**
+ * Clears the reset state, so queries know not to try again until the boundary is reset again.
+ */
+ clearReset: QueryErrorClearResetFunction
+ /**
+ * Returns whether the boundary has been reset and not yet cleared.
+ */
+ isReset: QueryErrorIsResetFunction
+ /**
+ * Resets any query errors within the boundary, so queries know they can try again.
+ */
+ reset: QueryErrorResetFunction
+}
+
+/**
+ * Creates the value shared through the boundary's context, which tracks whether a reset was
+ * requested.
+ * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary.
+ */
+function createValue(): QueryErrorResetBoundaryValue {
+ let isReset = false
+ return {
+ /**
+ * Clears the reset state, so queries know not to try again until the boundary is reset again.
+ */
+ clearReset: () => {
+ isReset = false
+ },
+ /**
+ * Resets any query errors within the boundary, so queries know they can try again.
+ */
+ reset: () => {
+ isReset = true
+ },
+ /**
+ * Returns whether the boundary has been reset and not yet cleared.
+ * @returns `true` if the boundary has been reset and not yet cleared.
+ */
+ isReset: () => {
+ return isReset
+ },
+ }
+}
+
+const QueryErrorResetBoundaryContext = React.createContext(createValue())
+
+// HOOK
+
+/**
+ * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
+ * defined it will reset them globally.
+ * @returns The boundary's {@link QueryErrorResetBoundaryValue}.
+ * @example
+ * ```tsx
+ * import { ErrorBoundary } from 'react-error-boundary'
+ * import { useQueryErrorResetBoundary } from '@tanstack/react-query-pluggable'
+ *
+ * function App({ children }: { children: React.ReactNode }) {
+ * const { reset } = useQueryErrorResetBoundary()
+ *
+ * return (
+ * (
+ *
+ * There was an error!
+ *
+ *
+ * )}
+ * >
+ * {children}
+ *
+ * )
+ * }
+ * ```
+ */
+export const useQueryErrorResetBoundary = () =>
+ React.useContext(QueryErrorResetBoundaryContext)
+
+// COMPONENT
+
+/**
+ * A render-prop function usable as `children` on `QueryErrorResetBoundary`.
+ * @param value - The boundary's {@link QueryErrorResetBoundaryValue}.
+ * @returns The children to render.
+ */
+export type QueryErrorResetBoundaryFunction = (
+ value: QueryErrorResetBoundaryValue,
+) => React.ReactNode
+
+/**
+ * The props accepted by `QueryErrorResetBoundary`.
+ */
+export interface QueryErrorResetBoundaryProps {
+ /**
+ * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and
+ * returns a node.
+ */
+ children: QueryErrorResetBoundaryFunction | React.ReactNode
+}
+
+/**
+ * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
+ * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
+ * reset any query errors within the boundaries of the component.
+ * @param props - The `children` to render.
+ * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}
+ * if `children` is a function.
+ * @example
+ * ```tsx
+ * import { ErrorBoundary } from 'react-error-boundary'
+ * import { QueryErrorResetBoundary } from '@tanstack/react-query-pluggable'
+ *
+ * function App() {
+ * return (
+ *
+ * {({ reset }) => (
+ * (
+ *
+ * )
+ * }
+ * ```
+ */
+ <
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+ >(
+ options: UnusedSkipTokenInfiniteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ): UnusedSkipTokenInfiniteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ > &
+ QueryKeyWithDataTag, TError>
+
+ /**
+ * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
+ * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`.
+ * `options.queryKey` is required and is the query key to generate options for.
+ * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
+ * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or
+ * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
+ * @see {@link useInfiniteQuery} to run an infinite query with these options.
+ * @example
+ * A parameterized factory, so the same options object can be reused per `postId`:
+ * ```tsx
+ * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable'
+ *
+ * export const commentsOptions = (postId: string) =>
+ * infiniteQueryOptions({
+ * queryKey: ['post', postId, 'comments'],
+ * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
+ * initialPageParam: 0,
+ * getNextPageParam: (lastPage) => lastPage.nextId,
+ * })
+ *
+ * function Comments({ postId }: { postId: string }) {
+ * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
+ *
+ * if (isPending) return 'Loading...'
+ * if (isError) return Error: {error.message}
+ *
+ * return (
+ *
+ * )
+ * }
+ * ```
+ */
+ <
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+ >(
+ options: UndefinedInitialDataInfiniteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ): UndefinedInitialDataInfiniteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ > &
+ QueryKeyWithDataTag, TError>
+}
+
+/** Preserves infinite query options and tags their key with the inferred pages and error types. */
+export const infiniteQueryOptions: InfiniteQueryOptionsFn = identity
diff --git a/packages/react-query-pluggable/src/mutationOptions.ts b/packages/react-query-pluggable/src/mutationOptions.ts
new file mode 100644
index 00000000000..91e9ab212fd
--- /dev/null
+++ b/packages/react-query-pluggable/src/mutationOptions.ts
@@ -0,0 +1,89 @@
+import { identity } from './runtime/identity'
+import type { DefaultError, WithRequired } from '@tanstack/query-core'
+import type { UseMutationOptions } from './types'
+
+type MutationOptionsFn = {
+ /**
+ * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A
+ * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
+ * `useMutationState`.
+ * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a
+ * required `mutationKey`.
+ * @returns The same options object, unchanged.
+ * @see {@link useMutation} to run the mutation these options describe.
+ * @example
+ * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
+ * ```tsx
+ * import { mutationOptions, useMutationState } from '@tanstack/react-query-pluggable'
+ *
+ * const createPostOptions = mutationOptions({
+ * mutationKey: ['posts', 'create'],
+ * mutationFn: createPost,
+ * })
+ *
+ * function SavingIndicator() {
+ * const isCreatingPost = useMutationState({
+ * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
+ * }).length > 0
+ *
+ * return isCreatingPost ? Saving… : null
+ * }
+ * ```
+ */
+ <
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = void,
+ TOnMutateResult = unknown,
+ >(
+ options: WithRequired<
+ UseMutationOptions,
+ 'mutationKey'
+ >,
+ ): WithRequired<
+ UseMutationOptions,
+ 'mutationKey'
+ >
+
+ /**
+ * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No
+ * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
+ * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,
+ * such as `status`.
+ * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a
+ * `mutationKey`.
+ * @returns The same options object, unchanged.
+ * @remarks See the other overload's example for looking a mutation up via `useMutationState`.
+ * @see {@link useMutation} to run the mutation these options describe.
+ * @example
+ * ```tsx
+ * import { mutationOptions, useMutation } from '@tanstack/react-query-pluggable'
+ *
+ * export const createPostOptions = mutationOptions({
+ * mutationFn: createPost,
+ * })
+ *
+ * function CreatePost() {
+ * const mutation = useMutation(createPostOptions)
+ * return
+ * }
+ * ```
+ */
+ <
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = void,
+ TOnMutateResult = unknown,
+ >(
+ options: Omit<
+ UseMutationOptions,
+ 'mutationKey'
+ >,
+ ): Omit<
+ UseMutationOptions,
+ 'mutationKey'
+ >
+}
+
+/** Preserves mutation option types when reusing the same options in multiple places. */
+export const mutationOptions: MutationOptionsFn = identity
diff --git a/packages/react-query-pluggable/src/queryOptions.ts b/packages/react-query-pluggable/src/queryOptions.ts
new file mode 100644
index 00000000000..616e93e043c
--- /dev/null
+++ b/packages/react-query-pluggable/src/queryOptions.ts
@@ -0,0 +1,249 @@
+import { identity } from './runtime/identity'
+import type {
+ DefaultError,
+ InitialDataFunction,
+ NonUndefinedGuard,
+ OmitKeyof,
+ QueryKey,
+ QueryKeyWithDataTag,
+} from '@tanstack/query-core'
+import type { DefaultQueryFn, SkipToken } from '@tanstack/query-core/primitives'
+import type { QueryFunction } from './runtime/types'
+import type { UseQueryOptions } from './types'
+
+/**
+ * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be
+ * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is
+ * `pending`.
+ * @template TQueryFnData - The type your `queryFn` resolves to.
+ * @template TError - The type of errors your `queryFn` may throw.
+ * @template TData - The type `data` ends up as after `select` runs.
+ * @template TQueryKey - The type of your `queryKey`.
+ */
+export type UndefinedInitialDataOptions<
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = TQueryFnData,
+ TQueryKey extends QueryKey = QueryKey,
+> = UseQueryOptions & {
+ /**
+ * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
+ * created or cached yet). If set to a function, the function will be called **once** during the shared/root
+ * query initialization, and be expected to synchronously return the initial data. Initial data is
+ * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
+ * cache.
+ */
+ initialData?:
+ | undefined
+ | InitialDataFunction>
+ | NonUndefinedGuard
+}
+
+/**
+ * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and
+ * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as
+ * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
+ * @template TQueryFnData - The type your `queryFn` resolves to.
+ * @template TError - The type of errors your `queryFn` may throw.
+ * @template TData - The type `data` ends up as after `select` runs.
+ * @template TQueryKey - The type of your `queryKey`.
+ */
+export interface UnusedSkipTokenOptions<
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = TQueryFnData,
+ TQueryKey extends QueryKey = QueryKey,
+> extends OmitKeyof<
+ UseQueryOptions,
+ 'queryFn'
+> {
+ /** The query function or the configured client default. */
+ queryFn: Exclude<
+ UseQueryOptions['queryFn'],
+ SkipToken
+ >
+}
+
+/**
+ * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined —
+ * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).
+ * @template TQueryFnData - The type your `queryFn` resolves to.
+ * @template TError - The type of errors your `queryFn` may throw.
+ * @template TData - The type `data` ends up as after `select` runs.
+ * @template TQueryKey - The type of your `queryKey`.
+ */
+export type DefinedInitialDataOptions<
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = TQueryFnData,
+ TQueryKey extends QueryKey = QueryKey,
+> = Omit, 'queryFn'> & {
+ /**
+ * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
+ * created or cached yet). If set to a function, the function will be called **once** during the shared/root
+ * query initialization, and be expected to synchronously return the initial data. Initial data is
+ * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
+ * cache.
+ */
+ initialData:
+ | NonUndefinedGuard
+ | (() => NonUndefinedGuard)
+ queryFn: QueryFunction | DefaultQueryFn
+}
+
+type QueryOptionsFn = {
+ /**
+ * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
+ * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and
+ * is the query key to generate options for.
+ *
+ * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never
+ * `undefined` (unless a `select` changes `TData` to include `undefined`).
+ * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined.
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
+ * @see {@link useQuery} to run a query with these options.
+ * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
+ * @example
+ * ```tsx
+ * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable'
+ *
+ * export const postsOptions = queryOptions({
+ * queryKey: ['posts'],
+ * queryFn: fetchPosts,
+ * initialData: [],
+ * })
+ *
+ * function Posts() {
+ * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
+ * // so the list stays visible alongside the error.
+ * const { data, isError, error } = useQuery(postsOptions)
+ *
+ * return (
+ *
+ * {isError ? Error: {error.message} : null}
+ *
+ * {data.map((post) =>
{post.title}
)}
+ *
+ *
+ * )
+ * }
+ * ```
+ */
+ <
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = TQueryFnData,
+ TQueryKey extends QueryKey = QueryKey,
+ >(
+ options: DefinedInitialDataOptions,
+ ): DefinedInitialDataOptions &
+ QueryKeyWithDataTag
+
+ /**
+ * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
+ * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and
+ * is the query key to generate options for.
+ * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`.
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
+ * @see {@link useQuery} to run a query with these options.
+ * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
+ * @example
+ * A parameterized factory, so the same options object can be reused per `id`:
+ * ```tsx
+ * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable'
+ *
+ * export const postOptions = (id: string) =>
+ * queryOptions({
+ * queryKey: ['post', id],
+ * queryFn: () => fetchPost(id),
+ * })
+ *
+ * function Post({ id }: { id: string }) {
+ * const { data, isPending, isError, error } = useQuery(postOptions(id))
+ *
+ * if (isPending) return 'Loading...'
+ * if (isError) return Error: {error.message}
+ *
+ * return
{data.title}
+ * }
+ * ```
+ */
+ <
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = TQueryFnData,
+ TQueryKey extends QueryKey = QueryKey,
+ >(
+ options: UnusedSkipTokenOptions,
+ ): UnusedSkipTokenOptions &
+ QueryKeyWithDataTag
+
+ /**
+ * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
+ * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and
+ * is the query key to generate options for.
+ * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
+ * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
+ * @see {@link useQuery} to run a query with these options.
+ * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
+ * @example
+ * A parameterized factory, so the same options object can be reused per `id`:
+ * ```tsx
+ * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable'
+ *
+ * export const postOptions = (id: string) =>
+ * queryOptions({
+ * queryKey: ['post', id],
+ * queryFn: () => fetchPost(id),
+ * })
+ *
+ * function Post({ id }: { id: string }) {
+ * const { data, isPending, isError, error } = useQuery(postOptions(id))
+ *
+ * if (isPending) return 'Loading...'
+ * if (isError) return Error: {error.message}
+ *
+ * return
{data.title}
+ * }
+ * ```
+ * @example
+ * A factory that disables the query, type safe, until `postId` is set:
+ * ```tsx
+ * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-pluggable'
+ *
+ * export const postOptions = (postId: number | undefined) =>
+ * queryOptions({
+ * queryKey: ['post', postId],
+ * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
+ * })
+ *
+ * function Post({ postId }: { postId: number | undefined }) {
+ * const { data, isLoading, isError, error } = useQuery(postOptions(postId))
+ *
+ * if (postId == null) return 'Select a post'
+ * if (isLoading) return 'Loading...'
+ * if (isError) return Error: {error.message}
+ *
+ * return
{data?.title}
+ * }
+ * ```
+ */
+ <
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = TQueryFnData,
+ TQueryKey extends QueryKey = QueryKey,
+ >(
+ options: UndefinedInitialDataOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey
+ >,
+ ): UndefinedInitialDataOptions &
+ QueryKeyWithDataTag
+}
+
+/** Preserves query options and tags their key with the inferred data and error types. */
+export const queryOptions: QueryOptionsFn = identity
diff --git a/packages/react-query-pluggable/src/runtime/cacheOperations.ts b/packages/react-query-pluggable/src/runtime/cacheOperations.ts
new file mode 100644
index 00000000000..d5eeb9b972a
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/cacheOperations.ts
@@ -0,0 +1,283 @@
+import { noop } from '@tanstack/query-core/primitives'
+import { notifyManager } from './notifyManager'
+import { getQueryCache, setQueryData } from './queryClient'
+import type { Updater } from '@tanstack/query-core/primitives'
+import type { QueryClient } from './queryClient'
+import type {
+ CancelOptions,
+ InvalidateOptions,
+ InvalidateQueryFilters,
+ QueryKey,
+ RefetchOptions,
+ RefetchQueryFilters,
+ ResetOptions,
+ SetDataOptions,
+} from './types'
+import type { QueryFilters } from './utils'
+
+/**
+ * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.
+ * Only queries matching the given filters are returned; if none match, an empty array is
+ * returned.
+ *
+ * Because the matched queries can hold data of different shapes (e.g. a broad filter can match
+ * queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather
+ * than being inferred. Passing a more specific type is a convenience for call sites that know
+ * every matched query holds the same shape — it is not checked against the actual cache
+ * contents.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to read.
+ * @returns An array of query key and data pairs. The data is `undefined` for a query with no cached data.
+ * @see {@link getQueryData}
+ * @example
+ * ```ts
+ * const data = getQueriesData(queryClient, { queryKey: ['posts'] })
+ * ```
+ */
+export function getQueriesData<
+ TQueryFnData = unknown,
+ TQueryFilters extends QueryFilters = QueryFilters,
+>(
+ client: QueryClient,
+ filters: TQueryFilters,
+): Array<[QueryKey, TQueryFnData | undefined]> {
+ return getQueryCache(client)
+ .findAll(filters)
+ .map(({ queryKey, state }) => {
+ const data = state.data as TQueryFnData | undefined
+ return [queryKey, data]
+ })
+}
+
+/**
+ * Synchronous way to immediately update the cached data of multiple queries at once, using
+ * filters or partial query key matching. Only queries that already exist and match the given
+ * filters are updated; no new cache entries are created. Internally this calls
+ * {@link setQueryData} for each matching query.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which existing queries to update.
+ * @param updater - Either the new data, or a function that receives each matched query's current
+ * data (which may be `undefined`) and returns the new data.
+ * @param options - Set `updatedAt` to override the timestamp the written data is recorded with.
+ * @returns One `[queryKey, data]` tuple per matched query, in the same shape and with the same
+ * `undefined` case as {@link setQueryData}.
+ * @example
+ * ```ts
+ * setQueriesData(queryClient, { queryKey: ['posts'] }, (oldPosts) =>
+ * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts)
+ * ```
+ */
+export function setQueriesData<
+ TQueryFnData,
+ TQueryFilters extends QueryFilters = QueryFilters,
+>(
+ client: QueryClient,
+ filters: TQueryFilters,
+ updater: Updater<
+ NoInfer | undefined,
+ NoInfer | undefined
+ >,
+ options?: SetDataOptions,
+): Array<[QueryKey, TQueryFnData | undefined]> {
+ return notifyManager.batch(() =>
+ getQueryCache(client)
+ .findAll(filters)
+ .map(({ queryKey }) => [
+ queryKey,
+ setQueryData(client, queryKey, updater, options),
+ ]),
+ )
+}
+
+/**
+ * Removes queries from the cache that match the given filters. Unlike
+ * {@link invalidateQueries} or {@link refetchQueries}, this removes
+ * matching queries from the cache instead of refetching them. Without filters, every query in
+ * the cache is removed.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to remove. Without filters, every query
+ * is removed.
+ * @example
+ * ```ts
+ * removeQueries(queryClient, { queryKey: ['posts'], exact: true })
+ * ```
+ */
+export function removeQueries(
+ client: QueryClient,
+ filters?: QueryFilters,
+): void {
+ const queryCache = getQueryCache(client)
+ notifyManager.batch(() => {
+ queryCache.findAll(filters).forEach((query) => {
+ queryCache.remove(query)
+ })
+ })
+}
+
+/**
+ * Resets queries matching the given filters back to their initial state (e.g. any
+ * `initialData`), notifying subscribers rather than removing them. Active queries among the
+ * matched set are then refetched, and the returned promise resolves once that refetch settles.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to reset. Without filters, every query
+ * is reset.
+ * @param options - Passed to the refetch of the active matched queries, e.g. `cancelRefetch` and
+ * `throwOnError`.
+ * @returns A promise that resolves once the refetch of the active matched queries settles.
+ * @example
+ * ```ts
+ * await resetQueries(queryClient, { queryKey: ['posts'], exact: true })
+ * ```
+ */
+export function resetQueries(
+ client: QueryClient,
+ filters?: QueryFilters,
+ options?: ResetOptions,
+): Promise {
+ const queryCache = getQueryCache(client)
+
+ return notifyManager.batch(() => {
+ const matched = queryCache.findAll(filters)
+ const queriesToRefetch = new Set(matched)
+ matched.forEach((query) => {
+ query.reset()
+ })
+ return refetchQueries(
+ client,
+ {
+ type: 'active',
+ predicate: (query) => queriesToRefetch.has(query),
+ },
+ options,
+ )
+ })
+}
+
+/**
+ * Cancels outgoing fetches for queries matching the given filters. Most useful when performing
+ * optimistic updates, since any outgoing refetch that resolves afterwards would otherwise
+ * overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is
+ * reverted to its state before the outgoing fetch started.
+ *
+ * The returned promise never rejects, even if individual cancellations fail.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to cancel. Without filters, every query
+ * is cancelled.
+ * @param cancelOptions - Passed to each matched query's cancellation. `revert` defaults to
+ * `true`.
+ * @returns A promise that resolves once every cancellation has settled.
+ * @example
+ * ```ts
+ * await cancelQueries(queryClient, { queryKey: ['posts'], exact: true })
+ * ```
+ */
+export function cancelQueries(
+ client: QueryClient,
+ filters?: QueryFilters,
+ cancelOptions: CancelOptions = {},
+): Promise {
+ const defaultedCancelOptions = { revert: true, ...cancelOptions }
+
+ const promises = notifyManager.batch(() =>
+ getQueryCache(client)
+ .findAll(filters)
+ .map((query) => query.cancel(defaultedCancelOptions)),
+ )
+
+ return Promise.all(promises).then(noop, noop)
+}
+
+/**
+ * Marks queries matching the given filters as invalidated. Unlike
+ * {@link removeQueries}, invalidated queries stay in the cache.
+ *
+ * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via
+ * {@link refetchQueries}, using `filters.refetchType` if set, otherwise
+ * `filters.type`, otherwise `'active'`.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to invalidate, plus `refetchType` to
+ * control which of them to refetch afterwards. Without filters, every query is invalidated.
+ * @param options - Passed to {@link refetchQueries}, e.g. `cancelRefetch` and
+ * `throwOnError`.
+ * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is
+ * `'none'`.
+ * @example
+ * ```ts
+ * await invalidateQueries(queryClient, { queryKey: ['posts'], refetchType: 'active' })
+ * ```
+ */
+export function invalidateQueries(
+ client: QueryClient,
+ filters?: InvalidateQueryFilters,
+ options?: InvalidateOptions,
+): Promise {
+ return notifyManager.batch(() => {
+ getQueryCache(client)
+ .findAll(filters)
+ .forEach((query) => {
+ query.invalidate()
+ })
+
+ if (filters?.refetchType === 'none') {
+ return Promise.resolve()
+ }
+ return refetchQueries(
+ client,
+ {
+ ...filters,
+ type: filters?.refetchType ?? filters?.type ?? 'active',
+ },
+ options,
+ )
+ })
+}
+
+/**
+ * Refetches queries matching the given filters, regardless of whether they are stale. Without
+ * filters, every query in the cache is refetched. Queries that are disabled, or static (only
+ * have observers with a static `staleTime`), are never refetched.
+ *
+ * By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new
+ * one starts. The returned promise does not reject on individual query failures unless
+ * `throwOnError` is `true`.
+ *
+ * Initially paused fetches do not delay the returned promise. Their later errors are handled
+ * even when `throwOnError` is `true`.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to refetch. Without filters, every query
+ * in the cache is included.
+ * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
+ * it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails.
+ * @returns A promise that resolves once all matching refetches that were not initially paused
+ * have settled.
+ * @example
+ * ```ts
+ * // refetch all active queries partially matching a query key:
+ * await refetchQueries(queryClient, { queryKey: ['posts'], type: 'active' })
+ * ```
+ */
+export function refetchQueries(
+ client: QueryClient,
+ filters?: RefetchQueryFilters,
+ options?: RefetchOptions,
+): Promise {
+ const fetchOptions = {
+ ...options,
+ cancelRefetch: options?.cancelRefetch ?? true,
+ }
+ const promises = notifyManager.batch(() =>
+ getQueryCache(client)
+ .findAll(filters)
+ .filter((query) => !query.isDisabled() && !query.isStatic())
+ .map((query) => {
+ let promise = query.fetch(undefined, fetchOptions)
+ const isPaused = query.state.fetchStatus === 'paused'
+ if (!fetchOptions.throwOnError || isPaused) {
+ promise = promise.catch(noop)
+ }
+ return isPaused ? Promise.resolve() : promise
+ }),
+ )
+
+ return Promise.all(promises).then(noop)
+}
diff --git a/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts b/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts
new file mode 100644
index 00000000000..4d9b666a424
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts
@@ -0,0 +1,105 @@
+import { infiniteFetchOptions } from './infiniteQueryBehavior'
+import { fetchQuery } from './queryClient'
+import type { QueryClient, WithoutSkipToken } from './queryClient'
+import type {
+ DefaultError,
+ InfiniteData,
+ InfiniteQueryExecuteOptions,
+ QueryKey,
+} from './types'
+
+/**
+ * Asynchronous method to fetch and cache an infinite query, resolving with an
+ * {@link InfiniteData} object or throwing with the error.
+ *
+ * Requires `initialPageParam` and `getNextPageParam`. Use `pages` to specify how many
+ * pages to fetch. If you omit `pages`, the client fetches up to the number of cached
+ * pages, or one page if the cache has no pages.
+ * If shared infinite query options contain `skipToken` as their `queryFn`, the call skips fetching
+ * and resolves with existing data or `undefined` on a cache miss. Use {@link getQueryData}
+ * to read the cache directly.
+ * @param client - The client that stores the query.
+ * @param options - The query to fetch and the options that control which pages to fetch.
+ * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if
+ * provided. It rejects with the error from the fetch or from `select`.
+ * @example
+ * ```ts
+ * try {
+ * const data = await fetchInfiniteQuery(queryClient, {
+ * queryKey,
+ * queryFn,
+ * initialPageParam: 0,
+ * getNextPageParam: (lastPage) => lastPage.nextCursor,
+ * })
+ * console.log(data.pages)
+ * } catch (error) {
+ * console.log(error)
+ * }
+ * ```
+ */
+export function fetchInfiniteQuery<
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+>(
+ client: QueryClient,
+ options: WithoutSkipToken<
+ InfiniteQueryExecuteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >
+ >,
+): Promise<
+ Array extends Array>
+ ? InfiniteData
+ : TData
+>
+export function fetchInfiniteQuery<
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+>(
+ client: QueryClient,
+ options: InfiniteQueryExecuteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+): Promise<
+ | undefined
+ | (Array extends Array>
+ ? InfiniteData
+ : TData)
+>
+export function fetchInfiniteQuery<
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+>(
+ client: QueryClient,
+ options: InfiniteQueryExecuteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+): Promise<
+ | undefined
+ | (Array extends Array>
+ ? InfiniteData
+ : TData)
+> {
+ return fetchQuery(client, infiniteFetchOptions(options) as any)
+}
diff --git a/packages/react-query-pluggable/src/runtime/hydration.ts b/packages/react-query-pluggable/src/runtime/hydration.ts
new file mode 100644
index 00000000000..27af3fd9f62
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/hydration.ts
@@ -0,0 +1,420 @@
+import { noop } from '@tanstack/query-core/primitives'
+import { prepareInfiniteFetch } from './infiniteQueryBehavior'
+import { Mutation } from './mutation'
+import {
+ getDefaultOptions,
+ getQueryCache,
+ mutationCacheKey,
+} from './queryClient'
+import { serialScope } from './serialScope'
+import type { DefaultError, DehydratedState } from '@tanstack/query-core'
+import type * as Core from '@tanstack/query-core'
+import type { Query } from './query'
+import type { QueryClient } from './queryClient'
+import type { MutationOptions, QueryOptions } from './types'
+
+type DehydratedMutation = DehydratedState['mutations'][number]
+
+type DehydratedQuery = DehydratedState['queries'][number]
+
+type TransformerFn = NonNullable
+
+/**
+ * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and
+ * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).
+ */
+export interface DehydrateOptions extends Omit<
+ Core.DehydrateOptions,
+ 'shouldDehydrateMutation' | 'shouldDehydrateQuery'
+> {
+ /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */
+ shouldDehydrateMutation?: (mutation: Mutation) => boolean
+ /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */
+ shouldDehydrateQuery?: (query: Query) => boolean
+}
+
+/**
+ * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a
+ * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.
+ */
+export interface HydrateOptions {
+ /** Options applied to the queries and mutations restored from the dehydrated state. */
+ defaultOptions?: {
+ /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */
+ deserializeData?: TransformerFn
+ /** Default options merged into every query restored from the dehydrated state. */
+ queries?: QueryOptions
+ /** Default options merged into every mutation restored from the dehydrated state. */
+ mutations?: MutationOptions
+ }
+}
+
+/**
+ * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that
+ * resolves within its `then` call.
+ * @param promise - The promise to read.
+ * @returns An object with the resolved `data`, or `undefined` if the promise hasn't resolved
+ * synchronously (or resolved with `undefined`).
+ */
+function tryResolveSync(promise: PromiseLike) {
+ let data: unknown
+
+ const thenResult = promise.then((result) => {
+ data = result
+ return result
+ }, noop) as Partial> | undefined
+
+ // A synchronous thenable may return an object without a catch method.
+ thenResult?.catch?.(noop)
+
+ if (data !== undefined) {
+ return { data }
+ }
+
+ return undefined
+}
+
+// FUNCTIONS
+
+/**
+ * Dehydrates a single `Mutation` into a serializable snapshot of its key, state, scope, and meta.
+ * @param mutation - The mutation to dehydrate.
+ * @returns The dehydrated mutation.
+ */
+function dehydrateMutation(mutation: Mutation): DehydratedMutation {
+ return {
+ mutationKey: mutation.options.mutationKey,
+ state: mutation.state,
+ ...(mutation.options.scope && { scope: { id: mutation.options.scope.id } }),
+ ...(mutation.meta && { meta: mutation.meta }),
+ }
+}
+
+/**
+ * Prepares the in-flight promise of a pending query for dehydration: applies `serializeData` to its
+ * result, and redacts its rejection error unless `shouldRedactErrors` returns `false` for it.
+ * @param query - The pending query whose promise is dehydrated.
+ * @param serializeData - Optional transform applied to the resolved data.
+ * @param shouldRedactErrors - Optional predicate; if it returns `false` for the rejection error,
+ * that
+ * error is kept as-is instead of being redacted.
+ * @returns The transformed promise, or `undefined` if the query has no in-flight promise.
+ */
+function dehydratePromise(
+ query: Query,
+ serializeData?: TransformerFn,
+ shouldRedactErrors?: (error: unknown) => boolean,
+): Promise | undefined {
+ const promise = query.promise?.then(serializeData).catch((error) => {
+ if (shouldRedactErrors?.(error) === false) {
+ // Reject original error if it should not be redacted
+ return Promise.reject(error)
+ }
+ // If not in production, log original error before rejecting redacted error
+ if (process.env.NODE_ENV !== 'production') {
+ console.error(
+ `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
+ )
+ }
+ return Promise.reject(new Error('redacted'))
+ })
+
+ // Avoid unhandled promise rejections
+ // We need the promise we dehydrate to reject to get the correct result into
+ // the query cache, but we also want to avoid unhandled promise rejections
+ // in whatever environment the prefetches are happening in.
+ promise?.catch(noop)
+
+ return promise
+}
+
+/**
+ * Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
+ * `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
+ * de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
+ * promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
+ * @param query - The query to dehydrate.
+ * @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
+ * @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
+ * error is kept as-is instead of being redacted.
+ * @returns The dehydrated query.
+ */
+export function dehydrateQuery(
+ query: Query,
+ serializeData?: TransformerFn,
+ shouldRedactErrors?: (error: unknown) => boolean,
+): DehydratedQuery {
+ return {
+ dehydratedAt: Date.now(),
+ state: {
+ ...query.state,
+ ...(query.state.data !== undefined && {
+ data: serializeData
+ ? serializeData(query.state.data)
+ : query.state.data,
+ }),
+ },
+ queryKey: query.queryKey,
+ queryHash: query.queryHash,
+ ...(query.state.status === 'pending' && {
+ promise: dehydratePromise(query, serializeData, shouldRedactErrors),
+ }),
+ ...(query.meta && { meta: query.meta }),
+ ...(query.queryType && { queryType: query.queryType }),
+ }
+}
+
+/**
+ * The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
+ * currently paused (e.g. paused by `networkMode` while offline).
+ * @param mutation - The mutation to check.
+ * @returns `true` if the mutation is paused.
+ */
+export function defaultShouldDehydrateMutation(mutation: Mutation) {
+ return mutation.state.isPaused
+}
+
+/**
+ * The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
+ * `'success'`.
+ * @param query - The query to check.
+ * @returns `true` if the query's status is `'success'`.
+ */
+export function defaultShouldDehydrateQuery(query: Query) {
+ return query.state.status === 'success'
+}
+
+/**
+ * Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
+ * typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
+ * Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
+ * falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
+ * `defaultShouldDehydrateMutation`.
+ * @param client - The client whose cache is dehydrated.
+ * @param options - Controls which queries and mutations are included and how their data and errors
+ * are transformed. Each option falls back to the client's `defaultOptions.dehydrate`.
+ * @returns The dehydrated state, with the included `queries` and `mutations`.
+ * @example
+ * ```ts
+ * const queryClient = new QueryClient()
+ *
+ * await fetchQuery(queryClient, {
+ * queryKey: ['posts'],
+ * queryFn: getPosts,
+ * })
+ *
+ * const dehydratedState = dehydrate(queryClient)
+ * ```
+ */
+export function dehydrate(
+ client: QueryClient,
+ options: DehydrateOptions = {},
+): DehydratedState {
+ const filterMutation =
+ options.shouldDehydrateMutation ??
+ getDefaultOptions(client).dehydrate?.shouldDehydrateMutation ??
+ defaultShouldDehydrateMutation
+
+ const mutations =
+ client[mutationCacheKey]
+ ?.getAll()
+ .flatMap((mutation) =>
+ filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
+ ) ?? []
+
+ const filterQuery =
+ options.shouldDehydrateQuery ??
+ getDefaultOptions(client).dehydrate?.shouldDehydrateQuery ??
+ defaultShouldDehydrateQuery
+
+ const shouldRedactErrors =
+ options.shouldRedactErrors ??
+ getDefaultOptions(client).dehydrate?.shouldRedactErrors
+
+ const serializeData =
+ options.serializeData ?? getDefaultOptions(client).dehydrate?.serializeData
+
+ const queries = getQueryCache(client)
+ .getAll()
+ .flatMap((query) =>
+ filterQuery(query)
+ ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
+ : [],
+ )
+
+ return { mutations, queries }
+}
+
+/**
+ * Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
+ * client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
+ * Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
+ * when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
+ * to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
+ * promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
+ * `queryFn`.
+ * @param client - The client whose cache is restored into.
+ * @param dehydratedState - The dehydrated state, e.g. produced by `dehydrate` on the server.
+ * @param options - `defaultOptions` merged into every restored query and mutation (on top of the
+ * client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`.
+ * @example
+ * ```ts
+ * // dehydratedState was produced by `dehydrate` on the server
+ * // and sent to the client, e.g. embedded in server-rendered markup.
+ * const queryClient = new QueryClient()
+ *
+ * hydrate(queryClient, dehydratedState)
+ * ```
+ */
+export function hydrate(
+ client: QueryClient,
+ dehydratedState: Partial,
+ options?: HydrateOptions,
+): void {
+ dehydratedState.mutations?.forEach(({ state, scope, ...mutationOptions }) => {
+ Mutation.build(
+ client,
+ {
+ ...getDefaultOptions(client).hydrate?.mutations,
+ ...options?.defaultOptions?.mutations,
+ ...mutationOptions,
+ ...(scope && { scope: serialScope(scope.id) }),
+ },
+ state,
+ )
+ })
+
+ if (dehydratedState.queries)
+ hydrateQueries(client, dehydratedState.queries, options)
+}
+
+/**
+ * Restores just the queries accepted by a React hydration boundary.
+ * @internal
+ * @param client - The client receiving the entries.
+ * @param queries - The serialized query entries.
+ * @param options - Query restoration settings.
+ */
+export function hydrateQueries(
+ client: QueryClient,
+ queries: Array,
+ options?: HydrateOptions,
+): void {
+ const queryCache = getQueryCache(client)
+ const deserializeData =
+ options?.defaultOptions?.deserializeData ??
+ getDefaultOptions(client).hydrate?.deserializeData
+
+ queries.forEach(
+ ({
+ queryKey,
+ state,
+ queryHash,
+ meta,
+ promise,
+ dehydratedAt,
+ queryType,
+ }) => {
+ const syncData = promise ? tryResolveSync(promise) : undefined
+ const rawData = state.data === undefined ? syncData?.data : state.data
+ const data =
+ rawData === undefined
+ ? rawData
+ : deserializeData
+ ? deserializeData(rawData)
+ : rawData
+
+ let query = queryCache.get(queryHash)
+ const existingQueryIsPending = query?.state.status === 'pending'
+ const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'
+
+ // Do not hydrate if an existing query exists with newer data
+ if (query) {
+ const hasNewerSyncData =
+ syncData && dehydratedAt > query.state.dataUpdatedAt
+ if (
+ state.dataUpdatedAt > query.state.dataUpdatedAt ||
+ hasNewerSyncData
+ ) {
+ // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus
+ const { fetchStatus: _ignored, ...serializedState } = state
+ query.setState({
+ ...serializedState,
+ data,
+ // If the query was pending at the moment of dehydration, but resolved to have data
+ // before hydration, we can assume the query should be hydrated as successful.
+ //
+ // Since you can opt into dehydrating failed queries, and those can have data from
+ // previous successful fetches, we make sure we only do this for pending queries.
+ ...(state.status === 'pending' &&
+ data !== undefined && {
+ status: 'success' as const,
+ dataUpdatedAt: dehydratedAt,
+ // Preserve existing fetchStatus if the existing query is actively fetching.
+ ...(!existingQueryIsFetching && {
+ fetchStatus: 'idle' as const,
+ }),
+ }),
+ })
+ }
+ } else {
+ // Restore query
+ query = queryCache.build(
+ client,
+ {
+ ...getDefaultOptions(client).hydrate?.queries,
+ ...options?.defaultOptions?.queries,
+ queryKey,
+ queryHash,
+ meta,
+ ...(queryType === 'infinite' && {
+ _type: queryType,
+ _prepareInfiniteFetch: prepareInfiniteFetch,
+ }),
+ },
+ // Reset fetch status to idle to avoid
+ // query being stuck in fetching state upon hydration
+ {
+ ...state,
+ data,
+ fetchStatus: 'idle',
+ // Like above, if the query was pending at the moment of dehydration but has data,
+ // we can assume it should be hydrated as successful.
+ status:
+ state.status === 'pending' && data !== undefined
+ ? 'success'
+ : state.status,
+ ...(state.status === 'pending' &&
+ data !== undefined && {
+ dataUpdatedAt: dehydratedAt,
+ }),
+ },
+ )
+ }
+
+ if (
+ promise &&
+ // If the data was synchronously available, there is no need to set up
+ // a retryer and thus no reason to call fetch
+ !syncData &&
+ !existingQueryIsPending &&
+ !existingQueryIsFetching &&
+ // Only hydrate if dehydration is newer than any existing data,
+ // this is always true for new queries
+ dehydratedAt > query.state.dataUpdatedAt
+ ) {
+ // This doesn't actually fetch - it just creates a retryer
+ // which will re-use the passed `initialPromise`
+ query
+ .fetch(undefined, {
+ // RSC transformed promises are not thenable
+ initialPromise: Promise.resolve(promise).then(deserializeData),
+ })
+ // Avoid unhandled promise rejections
+ .catch(noop)
+ }
+ },
+ )
+}
+
+export type { DehydratedState } from '@tanstack/query-core'
diff --git a/packages/react-query-pluggable/src/runtime/identity.ts b/packages/react-query-pluggable/src/runtime/identity.ts
new file mode 100644
index 00000000000..d6857688755
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/identity.ts
@@ -0,0 +1,9 @@
+/**
+ * Returns its argument by reference. Option helpers specialize the signature with
+ * their own overloads and add their key tags at compile time.
+ * @param value - The original value.
+ * @returns The original value.
+ */
+export function identity(value: T): T {
+ return value
+}
diff --git a/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts
new file mode 100644
index 00000000000..8a5d9a127ca
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts
@@ -0,0 +1,199 @@
+import {
+ addConsumeAwareSignal,
+ addToArray,
+ fetchSignal,
+} from '@tanstack/query-core/primitives'
+import { ensureQueryFn } from './utils'
+import type { FetchSignalContext } from '@tanstack/query-core/primitives'
+import type { FetchContext, Query } from './query'
+import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types'
+
+/**
+ * Installs the page fetcher for an infinite query. A retry continues from the
+ * failed page. A new fetch starts with the most recently cached pages.
+ * @param context - The fetch in progress, including its options and cached pages.
+ * @param query - The query supplied to a custom persister.
+ */
+export function prepareInfiniteFetch(
+ context: FetchContext>,
+ query: Query,
+): void {
+ const options = context.options as InfiniteQueryPageParamsOptions & {
+ pages?: number
+ }
+ const direction = context.fetchOptions?.meta?.fetchMore?.direction
+ const oldPages = context.state.data?.pages || []
+ const oldPageParams = context.state.data?.pageParams || []
+ let result: InfiniteData = { pages: [], pageParams: [] }
+ let currentPage = 0
+
+ const fetchFn = async () => {
+ let cancelled = false
+ const signalContext: FetchSignalContext = context
+ const queryFn = ensureQueryFn(context.options, context.fetchOptions)
+
+ // Create function to fetch a page
+ const fetchPage = async (
+ data: InfiniteData,
+ param: unknown,
+ previous?: boolean,
+ ): Promise> => {
+ if (cancelled) {
+ return Promise.reject(context.signal.reason)
+ }
+
+ if (param == null && data.pages.length) {
+ return Promise.resolve(data)
+ }
+
+ const queryFnContext = addConsumeAwareSignal(
+ {
+ client: context.client,
+ queryKey: context.queryKey,
+ pageParam: param,
+ meta: context.options.meta,
+ },
+ () => context.signal,
+ () => (cancelled = true),
+ signalContext[fetchSignal],
+ )
+
+ const page = await queryFn(queryFnContext)
+
+ const { maxPages } = context.options
+ return {
+ pages: addToArray(data.pages, page, maxPages, previous),
+ pageParams: addToArray(data.pageParams, param, maxPages, previous),
+ }
+ }
+
+ // fetch next / previous page?
+ if (direction && oldPages.length) {
+ const previous = direction === 'backward'
+ const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
+ const oldData = {
+ pages: oldPages,
+ pageParams: oldPageParams,
+ }
+ const param = pageParamFn(options, oldData)
+
+ result = await fetchPage(oldData, param, previous)
+ } else {
+ const remainingPages = options.pages ?? oldPages.length
+
+ // Fetch all pages
+ do {
+ const param =
+ currentPage === 0
+ ? oldPageParams[0] === undefined
+ ? options.initialPageParam
+ : oldPageParams[0]
+ : getNextPageParam(options, result)
+ if (currentPage > 0 && param == null) {
+ break
+ }
+ result = await fetchPage(result, param)
+ currentPage++
+ } while (currentPage < remainingPages)
+ }
+
+ return result
+ }
+ if (context.options.persister) {
+ context.fetchFn = () => {
+ return context.options.persister?.(
+ fetchFn as any,
+ {
+ client: context.client,
+ queryKey: context.queryKey,
+ meta: context.options.meta,
+ signal: context.signal,
+ },
+ query,
+ )
+ }
+ } else {
+ context.fetchFn = fetchFn
+ }
+}
+
+/**
+ * Computes the page param of the page after the last one, with the `getNextPageParam` option.
+ * @param options - The infinite query options.
+ * @param data - The current pages and page params.
+ * @returns The next page param, or `undefined` if there are no pages yet.
+ */
+function getNextPageParam(
+ options: InfiniteQueryPageParamsOptions,
+ { pages, pageParams }: InfiniteData,
+): unknown | undefined {
+ return pages.length > 0
+ ? options.getNextPageParam(
+ pages.at(-1),
+ pages,
+ pageParams.at(-1),
+ pageParams,
+ )
+ : undefined
+}
+
+/**
+ * Computes the page param of the page before the first one, with the `getPreviousPageParam`
+ * option.
+ * @param options - The infinite query options.
+ * @param data - The current pages and page params.
+ * @returns The previous page param, or `undefined` if there are no pages yet or no
+ * `getPreviousPageParam` option.
+ */
+function getPreviousPageParam(
+ options: InfiniteQueryPageParamsOptions,
+ { pages, pageParams }: InfiniteData,
+): unknown | undefined {
+ return pages.length > 0
+ ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
+ : undefined
+}
+
+/**
+ * Checks if there is a next page.
+ * @param options - The infinite query options with `getNextPageParam`.
+ * @param data - The current pages and page params.
+ * @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`.
+ */
+export function hasNextPage(
+ options: InfiniteQueryPageParamsOptions,
+ data?: InfiniteData,
+): boolean {
+ if (!data) return false
+ return getNextPageParam(options, data) != null
+}
+
+/**
+ * Checks if there is a previous page.
+ * @param options - The infinite query options with `getPreviousPageParam`.
+ * @param data - The current pages and page params.
+ * @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or
+ * `undefined`.
+ */
+export function hasPreviousPage(
+ options: InfiniteQueryPageParamsOptions,
+ data?: InfiniteData,
+): boolean {
+ if (!data || !options.getPreviousPageParam) return false
+ return getPreviousPageParam(options, data) != null
+}
+
+/**
+ * Attaches paging to the options that create or restore an infinite query.
+ * @param options - Options accepted by an infinite query or observer.
+ * @returns Options that install the page fetcher on the cached query.
+ */
+export function infiniteFetchOptions(
+ options: TOptions,
+) {
+ return {
+ ...options,
+ _type: 'infinite' as const,
+ _prepareInfiniteFetch: prepareInfiniteFetch,
+ }
+}
diff --git a/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts b/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts
new file mode 100644
index 00000000000..04555d44a81
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts
@@ -0,0 +1,290 @@
+import {
+ hasNextPage,
+ hasPreviousPage,
+ infiniteFetchOptions,
+} from './infiniteQueryBehavior'
+import { QueryObserver } from './queryObserver'
+import type { Subscribable } from '@tanstack/query-core/primitives'
+import type { Query } from './query'
+import type { QueryClient } from './queryClient'
+import type {
+ QueryObserverResultContext,
+ QueryObserverResultReader,
+} from './queryObserver'
+import type {
+ DefaultError,
+ DefaultedInfiniteQueryObserverOptions,
+ FetchNextPageOptions,
+ FetchPreviousPageOptions,
+ InfiniteData,
+ InfiniteQueryObserverBaseResult,
+ InfiniteQueryObserverOptions,
+ InfiniteQueryObserverResult,
+ QueryKey,
+ QueryObserverResult,
+} from './types'
+
+type InfiniteQueryObserverListener = (
+ result: InfiniteQueryObserverResult,
+) => void
+
+type ReplaceReturnType<
+ TFunction extends (...args: Array) => unknown,
+ TReturn,
+> = (...args: Parameters) => TReturn
+
+type InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey extends QueryKey,
+ TPageParam,
+> =
+ | InfiniteQueryObserverOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >
+ | DefaultedInfiniteQueryObserverOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >
+
+/**
+ * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
+ * between infinite queries. It augments the base `QueryObserverResult` with
+ * infinite-query-specific fields and methods, such as `hasNextPage` and
+ * `fetchNextPage`, and is the primitive that framework adapters (e.g.
+ * `useInfiniteQuery`) build their hooks on top of.
+ * @example
+ * ```ts
+ * const observer = new InfiniteQueryObserver(queryClient, {
+ * queryKey: ['projects'],
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
+ * initialPageParam: 0,
+ * getNextPageParam: (lastPage) => lastPage.nextCursor,
+ * })
+ *
+ * const unsubscribe = observer.subscribe((result) => console.log(result))
+ * ```
+ */
+export class InfiniteQueryObserver<
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+> extends QueryObserver<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+> {
+ // Type override
+ override subscribe!: Subscribable<
+ InfiniteQueryObserverListener
+ >['subscribe']
+
+ // Type override
+ override getCurrentResult!: ReplaceReturnType<
+ QueryObserver<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+ >['getCurrentResult'],
+ InfiniteQueryObserverResult
+ >
+
+ // Type override
+ protected override fetch!: ReplaceReturnType<
+ QueryObserver<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+ >['fetch'],
+ Promise>
+ >
+
+ constructor(
+ client: QueryClient,
+ options: InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ) {
+ super(client, options)
+ }
+
+ protected override bindMethods(): void {
+ super.bindMethods()
+ this.fetchNextPage = this.fetchNextPage.bind(this)
+ this.fetchPreviousPage = this.fetchPreviousPage.bind(this)
+ }
+
+ /**
+ * Updates the observer's options. Behaves the same as
+ * `QueryObserver.setOptions`, additionally marking the options as
+ * belonging to an infinite query before delegating to the base
+ * implementation.
+ * @param options - The new infinite query observer options.
+ */
+ override setOptions(
+ options: InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ): void {
+ super.setOptions(infiniteFetchOptions(options))
+ }
+
+ /**
+ * Creates a cached snapshot reader for an infinite query.
+ * @param options - The defaulted options used to read and commit the query result.
+ * @returns A reader that keeps its result and computation state until commit.
+ */
+ override createResultReader(
+ options: DefaultedInfiniteQueryObserverOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ): QueryObserverResultReader> {
+ return super.createResultReader(
+ infiniteFetchOptions(options),
+ ) as QueryObserverResultReader>
+ }
+
+ /**
+ * Fetches the next page of the infinite query and returns a promise that
+ * resolves with the resulting `InfiniteQueryObserverResult`. The page
+ * param used for the fetch is determined by `getNextPageParam`, which
+ * receives the current pages/page params and whose result also determines
+ * `hasNextPage`.
+ * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
+ * and `throwOnError` to `true` to reject when the fetch fails.
+ * @returns A promise that resolves with the result after the next page is fetched. With
+ * `cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched.
+ * @see {@link InfiniteQueryObserver#fetchPreviousPage}
+ * @example
+ * ```ts
+ * const { hasNextPage } = observer.getCurrentResult()
+ *
+ * if (hasNextPage) {
+ * await observer.fetchNextPage()
+ * }
+ * ```
+ */
+ fetchNextPage(
+ options?: FetchNextPageOptions,
+ ): Promise> {
+ return this.fetch({
+ ...options,
+ meta: {
+ fetchMore: { direction: 'forward' },
+ },
+ })
+ }
+
+ /**
+ * Fetches the previous page of the infinite query and returns a promise
+ * that resolves with the resulting `InfiniteQueryObserverResult`. The page
+ * param used for the fetch is determined by `getPreviousPageParam`, which
+ * receives the current pages/page params and whose result also determines
+ * `hasPreviousPage`.
+ * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
+ * and `throwOnError` to `true` to reject when the fetch fails.
+ * @returns A promise that resolves with the result after the previous page is fetched. With
+ * `cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched.
+ * @see {@link InfiniteQueryObserver#fetchNextPage}
+ * @example
+ * ```ts
+ * const { hasPreviousPage } = observer.getCurrentResult()
+ *
+ * if (hasPreviousPage) {
+ * await observer.fetchPreviousPage()
+ * }
+ * ```
+ */
+ fetchPreviousPage(
+ options?: FetchPreviousPageOptions,
+ ): Promise> {
+ return this.fetch({
+ ...options,
+ meta: {
+ fetchMore: { direction: 'backward' },
+ },
+ })
+ }
+
+ protected override createResult(
+ query: Query<
+ TQueryFnData,
+ TError,
+ InfiniteData,
+ TQueryKey
+ >,
+ options: InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ context?: QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+ >,
+ prevResult?: QueryObserverResult,
+ ): InfiniteQueryObserverResult {
+ const { state } = query
+ const parentResult = super.createResult(query, options, context, prevResult)
+
+ const { isFetching, isRefetching, isError, isRefetchError } = parentResult
+ const fetchDirection = state.fetchMeta?.fetchMore?.direction
+
+ const isFetchNextPageError = isError && fetchDirection === 'forward'
+ const isFetchingNextPage = isFetching && fetchDirection === 'forward'
+
+ const isFetchPreviousPageError = isError && fetchDirection === 'backward'
+ const isFetchingPreviousPage = isFetching && fetchDirection === 'backward'
+
+ const result: InfiniteQueryObserverBaseResult = {
+ ...parentResult,
+ fetchNextPage: this.fetchNextPage,
+ fetchPreviousPage: this.fetchPreviousPage,
+ hasNextPage: hasNextPage(options, state.data),
+ hasPreviousPage: hasPreviousPage(options, state.data),
+ isFetchNextPageError,
+ isFetchingNextPage,
+ isFetchPreviousPageError,
+ isFetchingPreviousPage,
+ isRefetchError:
+ isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
+ isRefetching:
+ isRefetching && !isFetchingNextPage && !isFetchingPreviousPage,
+ }
+
+ return result as InfiniteQueryObserverResult
+ }
+}
diff --git a/packages/react-query-pluggable/src/runtime/mutation.ts b/packages/react-query-pluggable/src/runtime/mutation.ts
new file mode 100644
index 00000000000..92fe8a700eb
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/mutation.ts
@@ -0,0 +1,501 @@
+import { Removable, createRetryer } from '@tanstack/query-core/primitives'
+import { getMutationCache } from './mutationCache'
+import { notifyManager } from './notifyManager'
+import { defaultMutationOptions } from './queryClient'
+import type { MutationState } from '@tanstack/query-core'
+import type {
+ MutationAction as Action,
+ Retryer,
+} from '@tanstack/query-core/primitives'
+import type { MutationCache } from './mutationCache'
+import type { MutationObserver } from './mutationObserver'
+import type { QueryClient } from './queryClient'
+import type {
+ DefaultError,
+ MutationFunctionContext,
+ MutationMeta,
+ MutationOptions,
+} from './types'
+
+interface MutationConfig {
+ client: QueryClient
+ mutationId: number
+ mutationCache: MutationCache
+ options: MutationOptions
+ state?: MutationState
+}
+
+// CLASS
+
+/**
+ * Represents a single mutation attempt. A `Mutation` holds the mutation's
+ * options, state (data/error/status), and the `MutationObserver`s currently
+ * subscribed to it.
+ *
+ * Instances are created and managed internally by `MutationCache`; application
+ * code typically interacts with mutations indirectly through `QueryClient` or
+ * a framework hook like `useMutation`. Direct access to a `Mutation` instance
+ * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
+ * ```
+ */
+export class Mutation<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = unknown,
+ TOnMutateResult = unknown,
+> extends Removable {
+ state: MutationState
+ options!: MutationOptions
+ readonly mutationId: number
+
+ #client: QueryClient
+ #observers: Array<
+ MutationObserver
+ >
+ #mutationCache: MutationCache
+ #retryer?: Retryer
+
+ /**
+ * Creates a mutation with the client's defaults and adds it to the cache.
+ * @param client - Supplies defaults and the mutation cache.
+ * @param options - The options for the new mutation.
+ * @param state - The initial state, for example when hydrating a paused mutation.
+ * @returns The registered mutation.
+ */
+ static build(
+ client: QueryClient,
+ options: MutationOptions,
+ state?: MutationState,
+ ): Mutation {
+ const cache = getMutationCache(client)
+ return cache.register(
+ (mutationId) =>
+ new Mutation({
+ client,
+ mutationCache: cache,
+ mutationId,
+ options: defaultMutationOptions(client, options),
+ state,
+ }),
+ )
+ }
+
+ constructor(
+ config: MutationConfig,
+ ) {
+ super()
+
+ this.#client = config.client
+ this.mutationId = config.mutationId
+ this.#mutationCache = config.mutationCache
+ this.#observers = []
+ this.state = config.state || getDefaultState()
+
+ this.options = config.options
+ this.updateGcTime(config.options.gcTime)
+ this.scheduleGc()
+ }
+
+ /**
+ * Replaces the mutation's options and applies their `gcTime`.
+ * @internal
+ * @param options - The new mutation options.
+ */
+ setOptions(
+ options: MutationOptions,
+ ): void {
+ // An observer may change options while its previous mutation is still queued.
+ const scope = this.options.scope
+ this.options = options.scope === scope ? options : { ...options, scope }
+ this.updateGcTime(options.gcTime)
+ }
+
+ /**
+ * The `meta` object passed in the mutation's options, if any.
+ * @returns The mutation's `meta`, or `undefined` if none was set.
+ */
+ get meta(): MutationMeta | undefined {
+ return this.options.meta
+ }
+
+ /**
+ * Subscribes an observer to the mutation and stops its garbage collection.
+ * @internal
+ * @param observer - The observer to add. Adding an observer that is already subscribed does
+ * nothing.
+ */
+ addObserver(observer: MutationObserver): void {
+ if (!this.#observers.includes(observer)) {
+ this.#observers.push(observer)
+
+ // Stop the mutation from being garbage collected
+ this.clearGcTimeout()
+
+ this.#mutationCache.notify({
+ type: 'observerAdded',
+ mutation: this,
+ observer,
+ })
+ }
+ }
+
+ /**
+ * Unsubscribes an observer from the mutation.
+ * @internal
+ * @param observer - The observer to remove. Schedules garbage collection if the mutation
+ * is still in the cache.
+ */
+ removeObserver(observer: MutationObserver): void {
+ this.#observers = this.#observers.filter((x) => x !== observer)
+
+ if (this.#mutationCache.has(this)) {
+ this.scheduleGc()
+ }
+
+ this.#mutationCache.notify({
+ type: 'observerRemoved',
+ mutation: this,
+ observer,
+ })
+ }
+
+ protected override optionalRemove() {
+ if (!this.#observers.length) {
+ if (this.state.status === 'pending') {
+ this.scheduleGc()
+ } else {
+ this.#mutationCache.remove(this)
+ }
+ }
+ }
+
+ /**
+ * Resumes a mutation that is currently paused or was restored from a
+ * dehydrated, still-`pending` state.
+ *
+ * - If this mutation has an active retryer (it paused mid-attempt, e.g. due
+ * to the network mode or scope-based queuing), its retryer is resumed.
+ * - Otherwise, if the mutation's status is still `pending` (e.g. it was
+ * dehydrated while an attempt was in flight and never got a retryer in
+ * this instance), `execute` is called again with the last known variables.
+ * - Otherwise the mutation has already settled and this resolves immediately
+ * without running anything again.
+ * @returns A promise that settles with the resumed mutation: it rejects if the mutation fails.
+ * It resolves immediately if the mutation has already settled.
+ * @see {@link Mutation#execute}
+ * @example
+ * ```ts
+ * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
+ * await mutation?.continue()
+ * ```
+ */
+ continue(): Promise {
+ return (
+ this.#retryer?.continue() ??
+ // continuing a mutation assumes that variables are set, mutation must have been dehydrated before.
+ // a settled mutation has no retryer to continue and must not run again
+ (this.state.status === 'pending'
+ ? this.execute(this.state.variables!)
+ : Promise.resolve())
+ )
+ }
+
+ /**
+ * Runs the mutation function for the given variables through a retryer, and
+ * drives the mutation's state and lifecycle callbacks through to settlement.
+ *
+ * If this mutation's state is already `pending` when `execute` is called
+ * (i.e. it was restored, still in-flight, from a dehydrated state), the
+ * `onMutate` step is skipped and a `continue` action is dispatched to
+ * unpause it; otherwise a `pending` action is dispatched first, then the
+ * mutation cache's `onMutate` and the mutation's own `onMutate` option are
+ * awaited in that order, and the resulting context is stored.
+ *
+ * The mutation function is then run (subject to `retry`/`retryDelay`/
+ * `networkMode`, and to the mutation cache's scope-based serialization).
+ * On success, the cache's `onSuccess`/`onSettled` callbacks run before the
+ * mutation's own `onSuccess`/`onSettled` options, a `success` action is
+ * dispatched, and the resolved data is returned. On failure, the same
+ * cache-then-option ordering is used for `onError`/`onSettled`, but each of
+ * those four callbacks is individually caught so that a throwing callback
+ * cannot mask the original error; an `error` action is then dispatched and
+ * the original error is re-thrown.
+ * @param variables - The variables passed to the `mutationFn`.
+ * @returns A promise that resolves with the mutation's data, or rejects with its error.
+ * @see {@link Mutation#continue}
+ * @example
+ * ```ts
+ * // Called internally by `MutationObserver.mutate` and `Mutation.continue` —
+ * // applications normally trigger mutations through those, not this method.
+ * const data = await mutation.execute(variables)
+ * ```
+ */
+ async execute(variables: TVariables): Promise {
+ const onContinue = () => {
+ this.#dispatch({ type: 'continue' })
+ }
+
+ const mutationFnContext = {
+ client: this.#client,
+ meta: this.options.meta,
+ mutationKey: this.options.mutationKey,
+ } satisfies MutationFunctionContext
+
+ const retryer = (this.#retryer = createRetryer({
+ fn: () => {
+ if (!this.options.mutationFn) {
+ return Promise.reject(new Error('No mutationFn found'))
+ }
+
+ return this.options.mutationFn(variables, mutationFnContext)
+ },
+ onFail: (failureCount, error) => {
+ this.#dispatch({ type: 'failed', failureCount, error })
+ },
+ onPause: () => {
+ this.#dispatch({ type: 'pause' })
+ },
+ onContinue,
+ retry: this.options.retry ?? 0,
+ retryDelay: this.options.retryDelay,
+ networkMode: this.options.networkMode,
+ canRun: () => this.#mutationCache.canRun(this),
+ }))
+
+ const restored = this.state.status === 'pending'
+ const isPaused = !retryer.canStart()
+
+ try {
+ if (restored) {
+ // Dispatch continue action to unpause restored mutation
+ onContinue()
+ } else {
+ this.#dispatch({ type: 'pending', variables, isPaused })
+ // Notify cache callback
+ if (this.#mutationCache.config.onMutate) {
+ await this.#mutationCache.config.onMutate(
+ variables,
+ this as Mutation,
+ mutationFnContext,
+ )
+ }
+ const context = await this.options.onMutate?.(
+ variables,
+ mutationFnContext,
+ )
+ if (context !== this.state.context) {
+ this.#dispatch({
+ type: 'pending',
+ context,
+ variables,
+ isPaused,
+ })
+ }
+ }
+ // Unpause a mutation that became able to start while onMutate was running
+ if (this.state.isPaused && retryer.canStart()) {
+ onContinue()
+ }
+ const data = await retryer.start()
+
+ // Notify cache callback
+ await this.#mutationCache.config.onSuccess?.(
+ data,
+ variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+
+ await this.options.onSuccess?.(
+ data,
+ variables,
+ this.state.context!,
+ mutationFnContext,
+ )
+
+ // Notify cache callback
+ await this.#mutationCache.config.onSettled?.(
+ data,
+ null,
+ this.state.variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+
+ await this.options.onSettled?.(
+ data,
+ null,
+ variables,
+ this.state.context,
+ mutationFnContext,
+ )
+
+ this.#dispatch({ type: 'success', data })
+ return data
+ } catch (error) {
+ try {
+ // Notify cache callback
+ await this.#mutationCache.config.onError?.(
+ error as any,
+ variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ try {
+ await this.options.onError?.(
+ error as TError,
+ variables,
+ this.state.context,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ try {
+ // Notify cache callback
+ await this.#mutationCache.config.onSettled?.(
+ undefined,
+ error as any,
+ this.state.variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ try {
+ await this.options.onSettled?.(
+ undefined,
+ error as TError,
+ variables,
+ this.state.context,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ this.#dispatch({ type: 'error', error: error as TError })
+ throw error
+ } finally {
+ // The settled retryer's promise would otherwise pin this mutation's
+ // result, variables and context for as long as the cache keeps it
+ if (this.#retryer === retryer) {
+ this.#retryer = undefined
+ }
+ this.#mutationCache.runNext(this)
+ }
+ }
+
+ #dispatch(action: Action): void {
+ const reducer = (
+ state: MutationState,
+ ): MutationState => {
+ switch (action.type) {
+ case 'failed':
+ return {
+ ...state,
+ failureCount: action.failureCount,
+ failureReason: action.error,
+ }
+ case 'pause':
+ return {
+ ...state,
+ isPaused: true,
+ }
+ case 'continue':
+ return {
+ ...state,
+ isPaused: false,
+ }
+ case 'pending':
+ return {
+ ...state,
+ context: action.context,
+ data: undefined,
+ failureCount: 0,
+ failureReason: null,
+ error: null,
+ isPaused: action.isPaused,
+ status: 'pending',
+ variables: action.variables,
+ submittedAt: Date.now(),
+ }
+ case 'success':
+ return {
+ ...state,
+ data: action.data,
+ failureCount: 0,
+ failureReason: null,
+ error: null,
+ status: 'success',
+ isPaused: false,
+ }
+ case 'error':
+ return {
+ ...state,
+ data: undefined,
+ error: action.error,
+ failureCount: state.failureCount + 1,
+ failureReason: action.error,
+ isPaused: false,
+ status: 'error',
+ }
+ }
+ }
+ this.state = reducer(this.state)
+
+ notifyManager.batch(() => {
+ this.#observers.forEach((observer) => {
+ observer.onMutationUpdate(action)
+ })
+ this.#mutationCache.notify({
+ mutation: this,
+ type: 'updated',
+ action,
+ })
+ })
+ }
+}
+
+/**
+ * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.
+ * @returns The initial mutation state.
+ */
+export function getDefaultState<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult,
+>(): MutationState {
+ return {
+ context: undefined,
+ data: undefined,
+ error: null,
+ failureCount: 0,
+ failureReason: null,
+ isPaused: false,
+ status: 'idle',
+ variables: undefined,
+ submittedAt: 0,
+ }
+}
+
+export type { MutationState } from '@tanstack/query-core'
+export type { MutationAction as Action } from '@tanstack/query-core/primitives'
diff --git a/packages/react-query-pluggable/src/runtime/mutationCache.ts b/packages/react-query-pluggable/src/runtime/mutationCache.ts
new file mode 100644
index 00000000000..110acf28dc1
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/mutationCache.ts
@@ -0,0 +1,345 @@
+import { Subscribable, noop } from '@tanstack/query-core/primitives'
+import { notifyManager } from './notifyManager'
+import { mutationCacheKey } from './queryClient'
+import { matchMutation } from './utils'
+import type {
+ CacheKeyConfig,
+ MutationKey,
+ NotifyEvent,
+} from '@tanstack/query-core'
+import type { MutationAction } from '@tanstack/query-core/primitives'
+import type { Mutation } from './mutation'
+import type { MutationObserver } from './mutationObserver'
+import type { QueryClient } from './queryClient'
+import type { DefaultError, MutationFunctionContext } from './types'
+import type { MutationFilters } from './utils'
+
+/**
+ * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which
+ * component or observer triggered it. They differ from the `defaultOptions` provided to a
+ * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these
+ * callbacks are always called, and `onMutate` here does not allow returning a result.
+ *
+ * If a callback returns a promise, it will be awaited before the mutation continues.
+ */
+export interface MutationCacheConfig {
+ /**
+ * Configures mutation key comparison and hashing globally.
+ * `equalityFn` compares individual values during partial matching and defaults to strict equality.
+ * `hashFn` hashes mutation keys for exact matching and mutation defaults.
+ */
+ mutationKey?: CacheKeyConfig
+ /** Called when any mutation in the cache encounters an error. */
+ onError?: (
+ error: DefaultError,
+ variables: unknown,
+ onMutateResult: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+ /** Called when any mutation in the cache is successful. */
+ onSuccess?: (
+ data: unknown,
+ variables: unknown,
+ onMutateResult: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+ /** Called before any mutation in the cache executes. */
+ onMutate?: (
+ variables: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+ /** Called when any mutation in the cache is settled, either successfully or with an error. */
+ onSettled?: (
+ data: unknown | undefined,
+ error: DefaultError | null,
+ variables: unknown,
+ onMutateResult: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+}
+
+/**
+ * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed
+ * from the cache, its state is updated, or one of its observers is added, removed, or has its
+ * options updated.
+ */
+export type MutationCacheNotifyEvent =
+ | NotifyEventMutationAdded
+ | NotifyEventMutationRemoved
+ | NotifyEventMutationObserverAdded
+ | NotifyEventMutationObserverRemoved
+ | NotifyEventMutationObserverOptionsUpdated
+ | NotifyEventMutationUpdated
+
+type MutationCacheListener = (event: MutationCacheNotifyEvent) => void
+
+interface NotifyEventMutationAdded extends NotifyEvent {
+ type: 'added'
+ mutation: Mutation
+}
+
+interface NotifyEventMutationRemoved extends NotifyEvent {
+ type: 'removed'
+ mutation: Mutation
+}
+
+interface NotifyEventMutationObserverAdded extends NotifyEvent {
+ type: 'observerAdded'
+ mutation: Mutation
+ observer: MutationObserver
+}
+
+interface NotifyEventMutationObserverRemoved extends NotifyEvent {
+ type: 'observerRemoved'
+ mutation: Mutation
+ observer: MutationObserver
+}
+
+interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {
+ type: 'observerOptionsUpdated'
+ mutation?: Mutation
+ observer: MutationObserver
+}
+
+interface NotifyEventMutationUpdated extends NotifyEvent {
+ type: 'updated'
+ mutation: Mutation
+ action: MutationAction
+}
+
+/**
+ * Returns the client's configured mutation cache, creating a default cache on
+ * first use. Mutation hooks and hydration share this cache.
+ * @param client - The client whose mutations you want to access.
+ * @returns The same mutation cache on every call for this client.
+ * @example
+ * ```ts
+ * import { getMutationCache } from '@tanstack/react-query-pluggable'
+ *
+ * const pending = getMutationCache(queryClient).findAll({ status: 'pending' })
+ * ```
+ */
+export function getMutationCache(client: QueryClient): MutationCache {
+ return (client[mutationCacheKey] ??= new MutationCache())
+}
+
+/**
+ * Stores the mutations executed through a client. Use {@link getMutationCache} to
+ * access the cache that mutation hooks use. Subscribe to it to receive updates
+ * when a mutation is added, removed, or changes state.
+ * @example
+ * ```ts
+ * const unsubscribe = mutationCache.subscribe((event) => {
+ * console.log(event.type, event.mutation)
+ * })
+ * ```
+ */
+export class MutationCache extends Subscribable {
+ #mutations: Set>
+ #mutationId: number
+
+ constructor(public config: MutationCacheConfig = {}) {
+ super()
+ this.#mutations = new Set()
+ this.#mutationId = 0
+ }
+
+ /**
+ * Assigns the next cache-local ID and registers the mutation.
+ * @internal
+ * @param create - Constructs the mutation with the assigned ID.
+ * @returns The mutation added to this cache.
+ */
+ register>(
+ create: (id: number) => T,
+ ): T {
+ const mutation = create(++this.#mutationId)
+ this.add(mutation)
+ return mutation
+ }
+
+ /**
+ * Adds a mutation to the cache.
+ * @internal
+ * @param mutation - The mutation to add. If it has a `scope`, it is queued in that scope.
+ */
+ add(mutation: Mutation): void {
+ this.#mutations.add(mutation)
+ mutation.options.scope?.add(this, mutation)
+ this.notify({ type: 'added', mutation })
+ }
+
+ /**
+ * Removes a mutation from the cache and clears its garbage collection timer.
+ * @internal
+ * @param mutation - The mutation to remove, also from its scope's queue.
+ */
+ remove(mutation: Mutation): void {
+ if (this.#mutations.delete(mutation)) {
+ mutation.destroy()
+ mutation.options.scope?.remove(this, mutation)
+ }
+
+ // Currently we notify the removal even if the mutation was already removed.
+ // Consider making this an error or not notifying of the removal depending on the desired semantics.
+ this.notify({ type: 'removed', mutation })
+ }
+
+ /**
+ * Checks whether this cache still holds the given mutation.
+ * @internal
+ * @param mutation - The mutation to check.
+ * @returns Whether the mutation is in the cache.
+ */
+ has(mutation: Mutation): boolean {
+ return this.#mutations.has(mutation)
+ }
+
+ /**
+ * Checks whether a mutation can run now, given the other mutations in its `scope`.
+ * @internal
+ * @param mutation - The mutation to check.
+ * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending
+ * ahead of it.
+ */
+ canRun(mutation: Mutation): boolean {
+ return mutation.options.scope?.canRun(this, mutation) ?? true
+ }
+
+ /**
+ * Continues the next paused mutation in the same `scope` after a mutation finishes.
+ * @internal
+ * @param mutation - The mutation that finished.
+ * @returns A promise that resolves once the next paused mutation in the same scope has continued,
+ * or immediately if there is none.
+ */
+ runNext(mutation: Mutation): Promise {
+ return mutation.options.scope?.runNext(this, mutation) ?? Promise.resolve()
+ }
+
+ /**
+ * Removes all mutations and clears their garbage collection timers.
+ * Mutations that are already running continue to execute.
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * mutationCache.clear()
+ * ```
+ */
+ clear(): void {
+ notifyManager.batch(() => {
+ const mutations = this.getAll()
+ this.#mutations.clear()
+ mutations.forEach((mutation) => {
+ mutation.options.scope?.remove(this, mutation)
+ mutation.destroy()
+ })
+ mutations.forEach((mutation) => {
+ this.notify({ type: 'removed', mutation })
+ })
+ })
+ }
+
+ /**
+ * Returns all mutations within the cache.
+ *
+ * This is not typically needed for most applications, but can come in handy when needing more
+ * information about a mutation in rare scenarios.
+ * @returns Every mutation in the cache.
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutations = mutationCache.getAll()
+ * ```
+ */
+ getAll(): Array {
+ return Array.from(this.#mutations)
+ }
+
+ /**
+ * A slightly more advanced method that can be used to get an existing mutation instance from
+ * the cache. If the mutation does not exist, `undefined` is returned.
+ *
+ * This is not typically needed for most applications, but can come in handy when needing more
+ * information about a mutation in rare scenarios.
+ * @param filters - The filters to match. `exact` defaults to `true`.
+ * @returns The first matching mutation, or `undefined`.
+ * @see {@link MutationCache#findAll}
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
+ * ```
+ */
+ find<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = any,
+ TOnMutateResult = unknown,
+ >(
+ filters: MutationFilters,
+ ): Mutation | undefined {
+ const defaultedFilters = { exact: true, ...filters }
+
+ return this.getAll().find((mutation) =>
+ matchMutation(defaultedFilters, mutation, this.config.mutationKey),
+ ) as Mutation | undefined
+ }
+
+ /**
+ * An even more advanced method that can be used to get existing mutation instances from the
+ * cache that match the given filters. If no mutations match, an empty array is returned.
+ *
+ * This is not typically needed for most applications, but can come in handy when needing more
+ * information about mutations in rare scenarios.
+ * @param filters - The filters to match. Without filters, every mutation is returned.
+ * @returns The matching mutations.
+ * @see {@link MutationCache#find}
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
+ * ```
+ */
+ findAll(filters: MutationFilters = {}): Array {
+ return this.getAll().filter((mutation) =>
+ matchMutation(filters, mutation, this.config.mutationKey),
+ )
+ }
+
+ /**
+ * Notifies every cache listener of an event, in one batch.
+ * @internal
+ * @param event - The event passed to every listener.
+ */
+ notify(event: MutationCacheNotifyEvent) {
+ notifyManager.batch(() => {
+ this.listeners.forEach((listener) => {
+ listener(event)
+ })
+ })
+ }
+
+ /**
+ * Continues every paused mutation, e.g. when the app comes back online.
+ * @internal
+ * @returns A promise that resolves once every paused mutation has continued and settled.
+ */
+ resumePausedMutations(): Promise {
+ const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
+
+ return notifyManager.batch(() =>
+ Promise.all(
+ pausedMutations.map((mutation) => mutation.continue().catch(noop)),
+ ),
+ )
+ }
+}
diff --git a/packages/react-query-pluggable/src/runtime/mutationObserver.ts b/packages/react-query-pluggable/src/runtime/mutationObserver.ts
new file mode 100644
index 00000000000..5e4b880940d
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/mutationObserver.ts
@@ -0,0 +1,330 @@
+import {
+ Subscribable,
+ hashKeyByOptions,
+ shallowEqualObjects,
+} from '@tanstack/query-core/primitives'
+import { Mutation, getDefaultState } from './mutation'
+import { getMutationCache } from './mutationCache'
+import { notifyManager } from './notifyManager'
+import { defaultMutationOptions } from './queryClient'
+import type { Action } from './mutation'
+import type { QueryClient } from './queryClient'
+import type {
+ DefaultError,
+ MutateOptions,
+ MutationFunctionContext,
+ MutationObserverOptions,
+ MutationObserverResult,
+} from './types'
+
+type MutationObserverListener = (
+ result: MutationObserverResult,
+) => void
+
+// CLASS
+
+/**
+ * Observes a single mutation and derives a `MutationObserverResult` from it.
+ * A framework hook like `useMutation` creates one `MutationObserver` per hook
+ * call, keeps it stable across re-renders, calls `setOptions` when the options
+ * passed to the hook change, subscribes to it to re-render on updates, and
+ * reads `getCurrentResult()` for the value to return. Calling `mutate()`
+ * builds a new underlying `Mutation` in the `MutationCache` and executes it.
+ * @example
+ * ```ts
+ * const observer = new MutationObserver(queryClient, {
+ * mutationFn: (variables: { title: string }) => addPost(variables),
+ * })
+ * ```
+ */
+export class MutationObserver<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = void,
+ TOnMutateResult = unknown,
+> extends Subscribable<
+ MutationObserverListener
+> {
+ options!: MutationObserverOptions
+
+ #client: QueryClient
+ #currentResult: MutationObserverResult<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ > = undefined!
+ #currentMutation?: Mutation
+ #mutateOptions?: MutateOptions
+
+ constructor(
+ client: QueryClient,
+ options: MutationObserverOptions<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ >,
+ ) {
+ super()
+
+ this.#client = client
+ this.setOptions(options)
+ this.bindMethods()
+ this.#updateResult()
+ }
+
+ /**
+ * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when
+ * destructured from it.
+ */
+ protected bindMethods(): void {
+ this.mutate = this.mutate.bind(this)
+ this.reset = this.reset.bind(this)
+ }
+
+ /**
+ * Updates the observer's options.
+ *
+ * If the new `mutationKey` differs from the previous one (and both were
+ * defined), the observer is reset, detaching it from the mutation it was
+ * observing. Otherwise, if the currently observed mutation is still
+ * `pending`, its options are updated in place as well.
+ * @param options - The new mutation observer options. They are defaulted with {@link
+ * defaultMutationOptions} before being applied.
+ * @example
+ * ```ts
+ * observer.setOptions({
+ * mutationFn: (variables: { title: string }) => addPost(variables),
+ * onSuccess: (data) => console.log(data),
+ * })
+ * ```
+ */
+ setOptions(
+ options: MutationObserverOptions<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ >,
+ ) {
+ const prevOptions = this.options as
+ | MutationObserverOptions
+ | undefined
+ this.options = defaultMutationOptions(this.#client, options)
+ const mutationCache = getMutationCache(this.#client)
+ if (!shallowEqualObjects(this.options, prevOptions)) {
+ mutationCache.notify({
+ type: 'observerOptionsUpdated',
+ mutation: this.#currentMutation,
+ observer: this,
+ })
+ }
+
+ if (
+ prevOptions?.mutationKey &&
+ this.options.mutationKey &&
+ hashKeyByOptions(
+ prevOptions.mutationKey,
+ mutationCache.config.mutationKey,
+ ) !==
+ hashKeyByOptions(
+ this.options.mutationKey,
+ mutationCache.config.mutationKey,
+ )
+ ) {
+ this.reset()
+ } else if (this.#currentMutation?.state.status === 'pending') {
+ this.#currentMutation.setOptions(this.options)
+ }
+ }
+
+ protected override onSubscribe(): void {
+ if (this.listeners.size === 1 && this.#currentMutation) {
+ this.#currentMutation.addObserver(this)
+
+ this.#updateResult()
+ }
+ }
+
+ protected override onUnsubscribe(): void {
+ if (!this.hasListeners()) {
+ this.#currentMutation?.removeObserver(this)
+ }
+ }
+
+ /**
+ * Updates the observer's result when the observed mutation changes, and notifies its listeners.
+ * @internal
+ * @param action - The action that updated the observed mutation, passed on to the observer's
+ * callbacks.
+ */
+ onMutationUpdate(
+ action: Action,
+ ): void {
+ this.#updateResult()
+
+ this.#notify(action)
+ }
+
+ /**
+ * Returns the observer's current result, derived from the observed
+ * mutation's state (or the default, `idle` state if no mutation has been
+ * built yet, e.g. before the first `mutate()` call or after `reset()`).
+ * @returns The observer's latest result.
+ */
+ getCurrentResult(): MutationObserverResult<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ > {
+ return this.#currentResult
+ }
+
+ /**
+ * Detaches the observer from the mutation it is currently observing (if
+ * any) and resets the observed result back to its default, `idle` state.
+ *
+ * This does not cancel an in-flight mutation; the mutation itself keeps
+ * running to completion and its own callbacks still fire, but this
+ * observer stops reflecting its state and a subsequent `mutate()` call
+ * will build a brand new mutation.
+ * @see {@link MutationObserver#mutate}
+ * @example
+ * ```ts
+ * observer.reset()
+ * ```
+ */
+ reset(): void {
+ // reset needs to remove the observer from the mutation because there is no way to "get it back"
+ // another mutate call will yield a new mutation!
+ this.#currentMutation?.removeObserver(this)
+ this.#currentMutation = undefined
+ this.#updateResult()
+ this.#notify()
+ }
+
+ /**
+ * Builds a new `Mutation` in the `MutationCache` using the observer's
+ * current options, detaches this observer from any previously observed
+ * mutation, attaches it to the new one, and executes it with the given
+ * variables.
+ *
+ * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
+ * invoked once the mutation settles, in addition to any callbacks defined
+ * on the observer's own options.
+ * @param variables - The variables passed to the `mutationFn`.
+ * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.
+ * @returns A promise that resolves with the mutation's data, or rejects with its error.
+ * @example
+ * ```ts
+ * await observer.mutate(
+ * { title: 'New post' },
+ * { onSuccess: (data) => console.log(data) },
+ * )
+ * ```
+ */
+ mutate(
+ variables: TVariables,
+ options?: MutateOptions,
+ ): Promise {
+ this.#mutateOptions = options
+
+ this.#currentMutation?.removeObserver(this)
+
+ this.#currentMutation = Mutation.build(this.#client, this.options)
+
+ this.#currentMutation.addObserver(this)
+
+ return this.#currentMutation.execute(variables)
+ }
+
+ #updateResult(): void {
+ const state =
+ this.#currentMutation?.state ??
+ getDefaultState()
+
+ this.#currentResult = {
+ ...state,
+ isPending: state.status === 'pending',
+ isSuccess: state.status === 'success',
+ isError: state.status === 'error',
+ isIdle: state.status === 'idle',
+ mutate: this.mutate,
+ reset: this.reset,
+ } as MutationObserverResult
+ }
+
+ #notify(action?: Action): void {
+ notifyManager.batch(() => {
+ // First trigger the mutate callbacks
+ // Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess)
+ // may call mutate() again, which overwrites this.#mutateOptions in place.
+ // Without the snapshot, onSettled would fire with the *next* mutation's
+ // options but the *current* mutation's data/variables.
+ const mutateOptions = this.#mutateOptions
+ if (mutateOptions && this.hasListeners()) {
+ const variables = this.#currentResult.variables!
+ const onMutateResult = this.#currentResult.context
+
+ const context = {
+ client: this.#client,
+ meta: this.options.meta,
+ mutationKey: this.options.mutationKey,
+ } satisfies MutationFunctionContext
+
+ if (action?.type === 'success') {
+ try {
+ mutateOptions.onSuccess?.(
+ action.data,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ try {
+ mutateOptions.onSettled?.(
+ action.data,
+ null,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ } else if (action?.type === 'error') {
+ try {
+ mutateOptions.onError?.(
+ action.error,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ try {
+ mutateOptions.onSettled?.(
+ undefined,
+ action.error,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ }
+ }
+
+ // Then trigger the listeners
+ this.listeners.forEach((listener) => {
+ listener(this.#currentResult)
+ })
+ })
+ }
+}
diff --git a/packages/react-query-pluggable/src/runtime/notifyManager.ts b/packages/react-query-pluggable/src/runtime/notifyManager.ts
new file mode 100644
index 00000000000..f7e49b01d06
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/notifyManager.ts
@@ -0,0 +1,127 @@
+type BatchCallsCallback> = (...args: T) => void
+
+type NotifyCallback = () => void
+
+type NotifyFunction = (callback: () => void) => void
+
+type ScheduleFunction = (callback: () => void) => void
+
+/**
+ * Default scheduling function used by the notify manager.
+ * Schedules the callback in a microtask with `queueMicrotask`.
+ */
+export const defaultScheduler: ScheduleFunction = queueMicrotask
+
+/**
+ * Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a
+ * single instance of it, exported as {@link notifyManager}.
+ * @returns A new notify manager.
+ */
+export function createNotifyManager() {
+ let queue: Array = []
+ let transactions = 0
+ let notifyFn: NotifyFunction = (callback) => {
+ callback()
+ }
+ let scheduleFn = defaultScheduler
+
+ const schedule = (callback: NotifyCallback): void => {
+ if (transactions) {
+ queue.push(callback)
+ } else {
+ scheduleFn(() => {
+ notifyFn(callback)
+ })
+ }
+ }
+ const flush = (): void => {
+ const originalQueue = queue
+ queue = []
+ if (originalQueue.length) {
+ scheduleFn(() => {
+ originalQueue.forEach((callback) => {
+ notifyFn(callback)
+ })
+ })
+ }
+ }
+
+ return {
+ /**
+ * Batches all updates scheduled inside the passed callback.
+ * This is mainly used internally to optimize query client updating.
+ * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
+ * The return value of `callback` is passed through.
+ * @param callback - The function to run in the batch.
+ * @returns The return value of `callback`.
+ */
+ batch: (callback: () => T): T => {
+ let result
+ transactions++
+ try {
+ result = callback()
+ } finally {
+ transactions--
+ if (!transactions) {
+ flush()
+ }
+ }
+ return result
+ },
+ /**
+ * All calls to the wrapped function will be batched.
+ * @param callback - The function to wrap.
+ * @returns A function that schedules a call to `callback` with the given arguments.
+ */
+ batchCalls: >(
+ callback: BatchCallsCallback,
+ ): BatchCallsCallback => {
+ return (...args) => {
+ schedule(() => {
+ callback(...args)
+ })
+ }
+ },
+ /**
+ * Schedules a function to be run on the next batch.
+ * By default, the batch runs in a microtask. Use `setScheduler` to change when it runs.
+ */
+ schedule,
+ /**
+ * Use this method to set a custom notify function.
+ * This can be used to for example wrap notifications with `React.act` while running tests.
+ * @param fn - Receives each notification callback and must call it.
+ */
+ setNotifyFunction: (fn: NotifyFunction) => {
+ notifyFn = fn
+ },
+ /**
+ * Configures a custom callback that schedules when the next batch runs.
+ * The default behavior is `queueMicrotask(callback)`.
+ * @param fn - Receives a callback that runs the next batch, and schedules it.
+ * @example
+ * ```ts
+ * import { notifyManager } from '@tanstack/react-query-pluggable'
+ *
+ * // Use the v5 timer-based scheduler
+ * notifyManager.setScheduler((cb) => setTimeout(cb, 0))
+ *
+ * // Schedule batches before the next frame is rendered
+ * notifyManager.setScheduler(requestAnimationFrame)
+ *
+ * // Schedule batches some time in the future
+ * notifyManager.setScheduler((cb) => setTimeout(cb, 10))
+ * ```
+ */
+ setScheduler: (fn: ScheduleFunction) => {
+ scheduleFn = fn
+ },
+ } as const
+}
+
+// SINGLETON
+
+/**
+ * Handles scheduling and batching callbacks in TanStack Query.
+ */
+export const notifyManager = createNotifyManager()
diff --git a/packages/react-query-pluggable/src/runtime/placeholderData.ts b/packages/react-query-pluggable/src/runtime/placeholderData.ts
new file mode 100644
index 00000000000..75a3530f771
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/placeholderData.ts
@@ -0,0 +1,101 @@
+import {
+ replaceData,
+ shallowEqualObjects,
+} from '@tanstack/query-core/primitives'
+import { projectResult } from './projectResult'
+import type { Query } from './query'
+import type {
+ ProjectionFailure,
+ QueryObserverResultContext,
+} from './queryObserver'
+import type { QueryKey, QueryObserverOptionsBase } from './types'
+
+/* #__NO_SIDE_EFFECTS__ */
+/**
+ * Supplies temporary data while an observed query has no cached result.
+ * @param value - A placeholder value or a factory receiving the previous query and its data.
+ * @returns A query placeholder option.
+ */
+export function placeholderData(
+ value: TValue,
+): readonly [typeof placeholderData, TValue] {
+ return [placeholderData, value]
+}
+
+placeholderData.project = projectResult
+placeholderData.resolve = resolvePlaceholder
+
+/**
+ * Reuses a pending query's placeholder until its factory, source query or sharing policy changes.
+ * @param options - Options that supply the placeholder.
+ * @param context - This observer or reader's cached placeholder.
+ * @param previousData - The previous data for structural sharing.
+ * @param previousQuery - The last observed query with defined data.
+ * @returns Placeholder data or the error thrown by its factory.
+ */
+function resolvePlaceholder<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey extends QueryKey,
+>(
+ options: QueryObserverOptionsBase<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ context: QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ previousData: TData | undefined,
+ previousQuery: Query | undefined,
+): QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+>['placeholder'] {
+ const value = options.placeholderData![1]
+ const previousState = previousQuery?.state
+ const key: NonNullable['key'] = {
+ placeholderData: value,
+ structuralSharing: options.structuralSharing,
+ previousQuery,
+ previousState,
+ previousOptions: previousQuery?.options,
+ }
+ const memo = context.placeholder
+ if (shallowEqualObjects(key, memo?.key)) return memo
+
+ let input: TQueryData | undefined
+ let sourceQuery: typeof previousQuery
+ let failure: ProjectionFailure | undefined
+ if (typeof value === 'function') {
+ try {
+ input = (
+ value as unknown as (
+ previous: TQueryData | undefined,
+ query: typeof previousQuery,
+ ) => TQueryData | undefined
+ )(previousState?.data, previousQuery)
+ } catch (error) {
+ failure = { error: error as TError, errorUpdatedAt: Date.now() }
+ }
+ if (previousState?.data !== undefined) sourceQuery = previousQuery
+ } else {
+ input = value
+ }
+ if (input !== undefined)
+ input = replaceData(previousData, input as unknown, options) as TQueryData
+ return input !== undefined || failure
+ ? { key, input, sourceQuery, failure }
+ : undefined
+}
diff --git a/packages/react-query-pluggable/src/runtime/projectResult.ts b/packages/react-query-pluggable/src/runtime/projectResult.ts
new file mode 100644
index 00000000000..ecdf5182269
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/projectResult.ts
@@ -0,0 +1,89 @@
+import type { Query, QueryState } from './query'
+import type { QueryObserverResultContext } from './queryObserver'
+import type { QueryKey, QueryObserverOptionsBase } from './types'
+
+/**
+ * Computes the data, status and error visible to one observer.
+ * @param query - The query whose cached data is being read.
+ * @param state - The query state for this read, including optimistic fetch state.
+ * @param options - The selection, placeholder and structural sharing options.
+ * @param context - Memoized results for this observer or uncommitted result reader.
+ * @param previousData - The preceding observer result for structural sharing.
+ * @param previousQuery - The preceding query with defined cached data.
+ * @returns The projected fields, including whether the result contains placeholder data.
+ */
+export function projectResult<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey extends QueryKey,
+>(
+ query: Query,
+ state: QueryState,
+ options: QueryObserverOptionsBase<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ context: QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ previousData: TData | undefined,
+ previousQuery: Query | undefined,
+): Pick<
+ QueryState,
+ 'data' | 'status' | 'error' | 'errorUpdatedAt'
+> & { isPlaceholderData: boolean } {
+ context.project = projectResult
+ const { select, placeholderData } = options
+ context.placeholder =
+ state.data === undefined && state.status === 'pending' && placeholderData
+ ? placeholderData[0].resolve(
+ options,
+ context,
+ previousData,
+ previousQuery,
+ )
+ : undefined
+ const placeholder = context.placeholder
+ const input = placeholder ? placeholder.input : state.data
+ // A previously selected query may have lost its data even if this render has no selector.
+ if (
+ context.selected?.query &&
+ context.selected.query.state.data === undefined
+ ) {
+ context.selected = undefined
+ if (!context.selection?.failure) context.selection = undefined
+ }
+ if (select && input !== undefined) {
+ select[0].resolve(
+ options,
+ select[1],
+ context,
+ previousData,
+ input,
+ placeholder ? placeholder.sourceQuery : query,
+ )
+ } else {
+ context.selection = undefined
+ }
+ const failure = placeholder?.failure ?? context.selection?.failure
+ const isPlaceholderData = !!placeholder && input !== undefined && !failure
+ const { error, errorUpdatedAt } = failure ?? state
+ return {
+ data: context.selection
+ ? context.selected?.data
+ : (input as unknown as TData | undefined),
+ error,
+ errorUpdatedAt,
+ status: failure ? 'error' : isPlaceholderData ? 'success' : state.status,
+ isPlaceholderData,
+ }
+}
diff --git a/packages/react-query-pluggable/src/runtime/projectionTypes.ts b/packages/react-query-pluggable/src/runtime/projectionTypes.ts
new file mode 100644
index 00000000000..856fb0dfc7f
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/projectionTypes.ts
@@ -0,0 +1,20 @@
+import type { placeholderData } from './placeholderData'
+import type { select } from './select'
+
+/** A selector and its opt-in observer implementation. */
+export type Select = readonly [
+ feature: typeof select,
+ value: (data: TInput) => TData,
+]
+
+/** Placeholder data (or a factory) paired with its observer implementation. */
+export type PlaceholderData = readonly [
+ feature: typeof placeholderData,
+ value:
+ // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes all callable and constructable values
+ | (TData extends Function ? never : TData)
+ | ((
+ previousData: TData | undefined,
+ previousQuery: TQuery | undefined,
+ ) => TData | undefined),
+]
diff --git a/packages/react-query-pluggable/src/runtime/queriesObserver.ts b/packages/react-query-pluggable/src/runtime/queriesObserver.ts
new file mode 100644
index 00000000000..853e1ea15e2
--- /dev/null
+++ b/packages/react-query-pluggable/src/runtime/queriesObserver.ts
@@ -0,0 +1,476 @@
+import {
+ Subscribable,
+ replaceEqualDeep,
+ shallowEqualObjects,
+ shouldThrowError,
+} from '@tanstack/query-core/primitives'
+import { notifyManager } from './notifyManager'
+import { defaultQueryOptions } from './queryClient'
+import { QueryObserver } from './queryObserver'
+import type {
+ QueriesObserverOptions,
+ QueriesObserverResultReader,
+ QueryObserverResultReader,
+} from '@tanstack/query-core'
+import type { QueryClient } from './queryClient'
+import type { ObserverOptionsInput } from './queryObserver'
+import type {
+ DefaultedQueryObserverOptions,
+ QueryObserverResult,
+} from './types'
+
+type CombineContext = {
+ result?: Array
+ combine?: CombineFn
+ value?: TCombinedResult
+ queryHashes?: Array
+}
+
+type CombineFn = (
+ result: Array,
+) => TCombinedResult
+
+type QueriesObserverListener = (result: Array) => void
+
+type QueryObserverMatch = {
+ defaultedQueryOptions: DefaultedQueryObserverOptions
+ observer: QueryObserver
+ reader?: QueryObserverResultReader
+}
+
+/**
+ * Returns the items of `array1` that are not in `array2`.
+ * @param array1 - The items to filter.
+ * @param array2 - The items to exclude.
+ * @returns A new array with the items of `array1` that are not in `array2`.
+ */
+function difference(array1: Array, array2: Array): Array {
+ const excludeSet = new Set(array2)
+ return array1.filter((x) => !excludeSet.has(x))
+}
+
+/**
+ * Compares two arrays of results by position and field value.
+ * @param result - The new results.
+ * @param previous - The previous results, if available.
+ * @returns Whether the results match.
+ */
+function equalResults(
+ result: Array,
+ previous: Array | undefined,
+): boolean {
+ return (
+ !!previous &&
+ result.length === previous.length &&
+ result.every((value, index) => shallowEqualObjects(value, previous[index]))
+ )
+}
+
+/**
+ * A `QueriesObserver` watches an array of queries at once, exposing them as
+ * a single array of `QueryObserverResult`s (or, when a `combine` option is
+ * given, as a combined value derived from that array). It manages one
+ * internal `QueryObserver` per query, and is the primitive that framework
+ * adapters (e.g. `useQueries`) build their hooks on top of.
+ * @example
+ * ```ts
+ * const observer = new QueriesObserver(queryClient, [
+ * { queryKey: ['post', 1], queryFn: fetchPost },
+ * { queryKey: ['post', 2], queryFn: fetchPost },
+ * ])
+ *
+ * const unsubscribe = observer.subscribe((result) => {
+ * console.log(result)
+ * })
+ * ```
+ */
+export class QueriesObserver<
+ TCombinedResult = Array,
+> extends Subscribable {
+ #client: QueryClient
+ #result: Array
+ #options?: QueriesObserverOptions
+ #observers: Array
+ #combinedResult?: TCombinedResult
+ #combineContext: CombineContext = {}
+ #observerMatches: Array = []
+ #updatingQueries = false
+
+ constructor(
+ client: QueryClient,
+ queries: Array>,
+ options?: QueriesObserverOptions,
+ ) {
+ super()
+
+ this.#client = client
+ this.#options = options
+ this.#observers = []
+ this.#result = []
+
+ this.setQueries(queries)
+ }
+
+ protected override onSubscribe(): void {
+ if (this.listeners.size === 1) {
+ this.#observers.forEach((observer) => this.#subscribeTo(observer))
+ }
+ }
+
+ protected override onUnsubscribe(): void {
+ if (!this.listeners.size) {
+ this.destroy()
+ }
+ }
+
+ /**
+ * Stops observing all queries: clears all listeners and destroys every
+ * underlying `QueryObserver` this observer manages.
+ */
+ destroy(): void {
+ this.listeners = new Set()
+ this.#observers.forEach((observer) => {
+ observer.destroy()
+ })
+ }
+
+ /**
+ * Replaces the set of queries being observed. Existing `QueryObserver`s
+ * are reused for queries that match an already-observed query hash;
+ * observers for queries that are no longer present are destroyed, and new
+ * observers are created and subscribed to for newly added queries.
+ * @param queries - The options of the queries to observe.
+ * @param options - Replaces the observer's options, e.g. its `combine` function.
+ * @example
+ * ```ts
+ * observer.setQueries([
+ * { queryKey: ['post', 1], queryFn: fetchPost },
+ * { queryKey: ['post', 3], queryFn: fetchPost },
+ * ])
+ * ```
+ */
+ setQueries(
+ queries: Array