Skip to main content

Migrating from TanStack Query

TanStack Query (React Query) caches each query key's response on its own, so the app keeps them consistent by invalidating keys after every mutation. Reactive Data Client normalizes responses into Entities: a mutation's response updates every list and detail that shows that entity, and most invalidation code goes away.

The migration replaces query functions and keys with typed endpoints, hooks with useSuspense() and Controller calls, and the QueryClient with DataProvider. Steps gives the order; API map gives the replacement for each TanStack Query API.

Migrate with your coding agent​

Paste this into your agent's chat:

Copy prompt for your coding agent

The setup skill follows this guide. Review its diff like a teammate's.

Steps​

Keep the app's tests passing after each step; they are the proof that behavior didn't change.

  1. Endpoints and schemas. Turn each query and mutation function into an endpoint: follow the REST setup for the HTTP library the functions call (axios, fetch, ky), then give each endpoint a schema built from Entities. Without a schema nothing is normalized, and you will need to keep every invalidateQueries call. Put the Entities and endpoints in one folder every feature may import (such as src/resources/), not in each feature's api/ folder, even when the query hooks lived there: a mutation in one feature often updates another feature's Entity. If lint rules restrict imports between folders (import/no-restricted-paths, eslint-plugin-boundaries, Nx module boundaries), use a shared layer they allow.
  2. Provider. Replace QueryClientProvider with DataProvider (Provider).
  3. Reads. Replace useQuery() and useSuspenseQuery() with useSuspense() in the component that renders the data (Reads).
  4. Mutations. Replace useMutation() with ctrl.fetch(), and delete the invalidation that normalization makes unneeded (Mutations).
  5. Loaders and prefetching. Replace queryClient in router loaders and hover prefetching with ctrl.fetchIfStale() (Loaders and prefetching).
  6. Infinite queries. Replace useInfiniteQuery() with a Collection and getPage (Infinite queries).
  7. Auth. Replace auth libraries built on TanStack Query, like react-query-auth (Auth).
  8. Tests. Replace QueryClientProvider in test wrappers, and loading-spinner assumptions (Tests).
  9. Clean up. Delete query key factories, queryOptions() helpers and lib/react-query.ts-style config. Uninstall @tanstack/react-query and @tanstack/react-query-devtools when no file imports them.

These steps keep the app's behavior, except where Data Client fixes it with less code: lists that showed stale data after a mutation, refetches after a mutation, and fetches for items a list already loaded. Changes that need extra code or change what users see, like adding optimistic updates the app did not have, are a separate, optional performance pass. Finish and check the migration first, so you can measure each stage.

API map​

TanStack QueryData Client
queryFn + queryKey, queryOptions()An endpoint with a schema. The endpoint and its args are the key, so key factories go away
useQuery(), useSuspenseQuery()useSuspense(endpoint, args): loading goes to the nearest <Suspense>, errors to the nearest error boundary, and data is never undefined
useQuery() where the component renders its own spinner or erroruseDLE(): { data, loading, error }
enabled: falsenull in place of the args: useSuspense(endpoint, id ? { id } : null) returns undefined and fetches nothing
selectCompute in render, or a Query schema read with useQuery()
useQueries()useFetch() for each, then React 19's use(): they fetch in parallel. On React 18, call useSuspense() for each after the useFetch() calls; it reuses their requests
staleTimedataExpiryLength on the endpoint or base class. The default is 60 seconds (TanStack Query's is 0)
gcTimeDataProvider's gcPolicy
retryDelete it: Data Client has no retry loop. An errored request is fetched again when a component needs it after errorExpiryLength (default 1 second), like TanStack Query's retry: false
refetchIntervalpollFrequency on the endpoint, read with useLive()
refetchOnWindowFocusDelete it: Data Client doesn't refetch on window focus. On React Native with React Navigation, a screen refetches its stale data when it regains focus
placeholderData: keepPreviousDataChange the args inside startTransition() (or useDebounce() for typed input): React keeps showing the current data while the next loads
initialData from a list queryDelete it: while the list's data is fresh, an Entity it loaded renders on the detail page without a fetch, when the detail endpoint's schema is that Entity
useMutation()ctrl.fetch(endpoint, ...args) in the event handler, from useController()
isPending, error of a mutationuseLoading(): const [run, isPending, error] = useLoading(fn, deps)
isSuccess, onSuccess, onErrorCode after or around await ctrl.fetch() (Mutations)
invalidateQueries() after an updateDelete it, when the response is the updated Entity
invalidateQueries() after a createctrl.fetch(Resource.getList.push, body) (or unshift); numbered pages differ (Mutations)
invalidateQueries() after a deleteDelete it: resource().delete (or a schema.Invalidate schema) removes the Entity from every list
invalidateQueries() for data the response doesn't include (counts, totals)ctrl.expireAll(endpoint): mounted components refetch
refetchQueries()ctrl.fetch(endpoint, args)
setQueryData()ctrl.setResponse(endpoint, args, response); for Entities, ctrl.set(Entity, args, value)
getQueryData()In a component, useCache(). Elsewhere, ctrl.get(schema, args, ctrl.getState())
prefetchQuery()ctrl.fetchIfStale(endpoint, args), not awaited: a failure never rejects unhandled
ensureQueryData(), getQueryData() ?? fetchQuery()Cached data from ctrl.getResponse() when it can render, else ctrl.fetchIfStale(endpoint, args) (Loaders)
fetchQuery()await ctrl.fetchIfStale(endpoint, args) with a staleTime; ctrl.fetch(endpoint, args) without
onMutate optimistic update and rollbackgetOptimisticResponse() on the endpoint: Data Client rolls back on error
useInfiniteQuery()A Collection and ctrl.fetch(endpoint.getPage, args) (Infinite queries)
onError on QueryCache or MutationCache (global error reporting)An error reporting Manager: it sees every failed fetch
queryClient.clear(), removeQueries() on logoutctrl.resetEntireStore()
QueryClientProvider, new QueryClient()DataProvider
useQueryClient()useController()
ReactQueryDevtoolsDelete it: DataProvider adds devtools in development
HydrationBoundary, dehydrate()Server Side Rendering
warning

Data Client's own useQuery() is not TanStack Query's. It reads a schema from the store and never fetches. Replace TanStack Query's useQuery() with useSuspense() or useDLE().

Provider​

Put DataProvider at the root, outside the app's other providers and <Suspense> boundaries, rather than where QueryClientProvider was. Its backup boundary, which shows "Uncaught Suspense" in development, catches before any boundary above it.

provider.tsx
import { DataProvider } from '@data-client/react';
import { Suspense, type ReactNode } from 'react';

export const AppProvider = ({ children }: { children: ReactNode }) => (
<DataProvider>
<Suspense fallback={<Loading />}>{children}</Suspense>
</DataProvider>
);

DataProvider makes its own store, so there is no client to create. Move QueryClient defaultOptions to the base endpoint class, as the API map lists.

Reads​

Call useSuspense() in the component that renders the data, and delete the per-feature useIssues() hook that wrapped useQuery(). Two components that ask for the same endpoint and args share one fetch and one store entry, so nothing is gained by sharing a hook, and a hook hides what the component depends on.

Before
export const issueKeys = {
all: ['issues'] as const,
list: (page: number) => [...issueKeys.all, 'list', page] as const,
detail: (id: number) => [...issueKeys.all, 'detail', id] as const,
};

export const useIssues = (page: number) =>
useQuery({ queryKey: issueKeys.list(page), queryFn: () => fetchIssues(page) });
Before, in IssueTable
const { data, isLoading, isError } = useIssues(page);
if (isLoading) return <TableSkeleton />;
if (isError) return <ErrorBanner />;
return <Table rows={data?.results ?? []} />;
After
import { useSuspense } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export function IssueTable({ page }: { page: number }) {
const { results: issues, pagination } = useSuspense(IssueResource.getList, {
page,
});
return (
<table>
<caption>
Page {pagination.page} of {pagination.pageCount}
</caption>
<tbody>
{issues.map(issue => (
<tr key={issue.id}>
<td>{issue.title}</td>
<td>{issue.state}</td>
</tr>
))}
</tbody>
</table>
);
}

The isLoading branch moves to a <Suspense> fallback, and the isError branch to an error boundary; an AsyncBoundary is both. Keep the app's own skeleton and error banner as their fallbacks. The ?? [] guard goes away, because useSuspense() returns only once data is there.

Two useSuspense() calls in one component load one after the other. When neither needs the other's data, start both with useFetch() and read them with use() (parallel data loading). On React 18, which has no use(), read them with useSuspense() after both useFetch() calls.

Envelope responses​

When the API wraps responses in an envelope (an outer object that holds the data next to metadata), like { "results": [...], "pagination": {...} }, make the envelope the schema, so components keep reading pagination:

resources/Issue.ts
import { Entity, resource } from '@data-client/rest';

export class Issue extends Entity {
id = 0;
title = '';
state: 'open' | 'closed' = 'open';
assignee = '';

static key = 'Issue';
}

interface Pagination {
page: number;
pageCount: number;
}

export const IssueResource = resource({
path: '/issues/:id',
searchParams: {} as { page?: number },
schema: Issue,
}).extend(Base => ({
getList: Base.getList.extend({
schema: { results: [Issue], pagination: {} as Pagination },
}),
// a new issue shifts every numbered page, so this POST joins no list: callers expire it
create: Base.getList.push.extend({ schema: Issue }),
}));

searchParams types the list's page argument. create reuses the list's POST, with the plain Issue schema in place of the list's Collection; Mutations says when to use it. When single items come wrapped too, like { "data": {...} }, extend get the same way: Base.get.extend({ schema: { data: Issue } }).

Mutations​

Call ctrl.fetch() where the app called mutate(). What onSuccess did goes after the await; onError goes in a catch. Track pending and error state with useLoading().

Before
export const useCloseIssue = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) => patchIssue(id, { state: 'closed' }),
onSuccess: issue => {
queryClient.invalidateQueries({ queryKey: issueKeys.detail(issue.id) });
toast(`Closed #${issue.id}`);
},
onError: () => toast('Could not close the issue'),
});
};
After
import { useController, useLoading } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export function CloseIssueButton({ id }: { id: number }) {
const ctrl = useController();
const [close, isPending] = useLoading(async () => {
try {
await ctrl.fetch(IssueResource.partialUpdate, { id }, { state: 'closed' });
toast(`Closed #${id}`);
} catch {
toast('Could not close the issue');
}
}, [ctrl, id]);
return (
<button onClick={close} disabled={isPending}>
Close issue
</button>
);
}

The invalidateQueries() call is gone: the response is the updated Issue, so the table and the detail page both show it closed. TanStack Query apps usually invalidate the detail key but not every list key, so lists show stale data until they expire; after the migration they don't.

Decide what to do with each invalidateQueries() and refetchQueries() call from the response (more examples in mutations):

  • Response is the changed Entity (update, partial update): delete the call, unless the change moves the Entity between filtered or sorted lists. Closing an issue updates it everywhere, but doesn't remove it from a cached ?state=open list or add it to a ?state=closed one; keep those right with ctrl.expireAll(Resource.getList).
  • Create: fetch the list's push (or unshift) endpoint instead of the plain POST, and the new Entity joins every matching list. This needs a Collection in the list's schema: resource() has one by default, and an envelope needs it inside, like results: new Collection([Issue]). For lists split into numbered pages, where a new item shifts every page, add a plain POST endpoint (create in the envelope example: Base.getList.push.extend({ schema: Issue })), then call ctrl.expireAll(Resource.getList).
  • Delete: resource().delete removes the Entity from every list. For a custom endpoint, use schema: new schema.Invalidate(MyEntity). For lists split into numbered pages, also call ctrl.expireAll(Resource.getList): the server's later items move up a page, which the cached pages can't know.
  • Data the response doesn't include (a count, another resource's totals): ctrl.expireAll(endpoint), or return it in the response (side effects).

Success state​

useLoading() has no isSuccess, and the function it returns never rejects: it stores the error instead. So close a form or dialog after await ctrl.fetch() inside the function you pass to useLoading(), not after calling the returned function. To keep a success flag:

useMutate.ts
import { useLoading } from '@data-client/react';
import { useState } from 'react';

export function useMutate<A extends unknown[]>(
mutate: (...args: A) => Promise<unknown>,
deps: readonly unknown[],
) {
const [isDone, setIsDone] = useState(false);
const [run, isPending, error] = useLoading(async (...args: A) => {
setIsDone(false);
await mutate(...args);
setIsDone(true);
}, deps);
return { run, isPending, error, isDone };
}

Loaders and prefetching​

Router loaders that receive the queryClient receive the Controller instead. useController() returns the same Controller on every render, so it is safe to create the router from it.

Before
export const issueLoader =
(queryClient: QueryClient) =>
({ params }: LoaderFunctionArgs) =>
queryClient.ensureQueryData({
queryKey: issueKeys.detail(Number(params.issueId)),
queryFn: () => fetchIssue(Number(params.issueId)),
});
After
import { ExpiryStatus, type Controller } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export const issueLoader =
(ctrl: Controller) =>
({ params }: { params: { issueId?: string } }) => {
const args = { id: Number(params.issueId) };
const { data, expiryStatus } = ctrl.getResponse(
IssueResource.get,
args,
ctrl.getState(),
);
// fetches only when missing or stale
const fetched = ctrl.fetchIfStale(IssueResource.get, args);
// like ensureQueryData(): cached data, even stale, navigates now; a miss waits for the fetch
return expiryStatus === ExpiryStatus.Valid ? data : fetched;
};

fetchIfStale() fetches only when the data is missing or stale, and always returns a Promise. Left unawaited, it works like prefetchQuery(): a failure never rejects unhandled, and is stored for components to show. Use it for hover or focus prefetching too: onMouseEnter={() => ctrl.fetchIfStale(IssueResource.get, { id })}. Awaited, it works like fetchQuery() with a staleTime: it resolves the data, waiting for the refetch when cached data is stale, or rejects with the error. Use the awaited form where the loader used fetchQuery(), and the pattern above where it used ensureQueryData() or getQueryData() ?? fetchQuery(). Route loaders shows loaders that don't make navigation wait. Load several endpoints the way the loader did before; letting the page show before secondary data arrives belongs to the performance pass.

Infinite queries​

useInfiniteQuery() keeps an array of pages. Data Client keeps one list: a Collection that each new page appends to. Set paginationField on the endpoint to get its getPage endpoint.

resources/Note.ts
import { Collection, Entity, RestEndpoint } from '@data-client/rest';

export class Note extends Entity {
id = 0;
text = '';
author = '';

static key = 'Note';
}

// every page of one issue's notes shares one list
const issueNotes = new Collection([Note], {
argsKey: ({ issueId }: { issueId: number }) => ({ issueId }),
});

export const getNotes = new RestEndpoint({
path: '/issues/:issueId/notes',
searchParams: {} as { page?: number },
schema: { results: issueNotes, nextPage: 0 as number | null },
paginationField: 'page',
});

export const addNote = new RestEndpoint({
path: '/issues/:issueId/notes',
method: 'POST',
body: {} as { text: string },
schema: issueNotes.push,
});

argsKey leaves out page, so every page and the push endpoint find the same list. A new note appears without invalidating anything.

IssueNotes.tsx
import { useController, useLoading, useSuspense } from '@data-client/react';
import { getNotes } from './resources/Note';

export function IssueNotes({ issueId }: { issueId: number }) {
const { results: notes, nextPage } = useSuspense(getNotes, { issueId });
const ctrl = useController();
const [loadMore, isLoadingMore] = useLoading(
async (page: number) => ctrl.fetch(getNotes.getPage, { issueId, page }),
[ctrl, issueId],
);
return (
<>
<ul>
{notes.map(note => (
<li key={note.id}>
{note.author}: {note.text}
</li>
))}
</ul>
{nextPage !== null && (
<button onClick={() => loadMore(nextPage)} disabled={isLoadingMore}>
Show older notes
</button>
)}
</>
);
}

pages.flatMap() goes away. What getNextPageParam computed and hasNextPage reported come from the response (nextPage here), which getPage updates along with the list. isFetchingNextPage is useLoading()'s pending flag. For cursors, see pagination.

Auth​

Libraries like react-query-auth give useUser(), useLogin(), useLogout() and AuthLoader on top of TanStack Query. Rebuild them from endpoints:

session.ts
import { useController, useLoading, useSuspense } from '@data-client/react';
import { Entity, RestEndpoint } from '@data-client/rest';

class Account extends Entity {
id = '';
displayName = '';

static key = 'Account';
}

const getSession = new RestEndpoint({
path: '/session',
schema: { account: Account },
});
const signIn = new RestEndpoint({
path: '/session',
method: 'POST',
body: {} as { username: string; password: string },
schema: { account: Account, token: '' },
});
const signOut = new RestEndpoint({ path: '/session', method: 'DELETE' });

export const useAccount = () => useSuspense(getSession).account;

export const useSignIn = (onSuccess?: () => void) => {
const ctrl = useController();
return useLoading(
async (body: { username: string; password: string }) => {
const { account } = await ctrl.fetch(signIn, body);
// the signed-in account becomes the current one without refetching
await ctrl.setResponse(getSession, { account });
onSuccess?.();
},
[ctrl, onSuccess],
);
};

export const useSignOut = (onSuccess?: () => void) => {
const ctrl = useController();
return useLoading(async () => {
await ctrl.fetch(signOut);
await ctrl.resetEntireStore();
onSuccess?.();
}, [ctrl, onSuccess]);
};

For sign-up, copy useSignIn() as useSignUp() with the sign-up endpoint and its body type. AuthLoader goes away: useAccount() suspends to the app's <Suspense> boundary until the session loads. These hooks wrap actions, not a data binding, so they are worth keeping as hooks.

Call sites change shape:

  • useUser().data becomes the value itself: useAccount().
  • useLogin({ onSuccess }).mutate(values) becomes const [signIn, isPending] = useSignIn(onSuccess), then signIn(values).

useAccount() needs /session to answer a signed-out visitor with no account, as react-query-auth's userFn returns null. Then signed-out pages render, and the refetch after resetEntireStore() shows the signed-out state. If the API answers 401 instead, the error reaches the nearest error boundary, so turn that status into a signed-out response:

getSession.ts
import { Entity, NetworkError, RestEndpoint } from '@data-client/rest';

class Account extends Entity {
id = '';
displayName = '';

static key = 'Account';
}

export const getSession = new RestEndpoint({
path: '/session',
schema: { account: Account },
async fetchResponse(input: RequestInfo, init: RequestInit) {
const response = await fetch(input, init);
if (response.status === 401) {
// parseResponse() reads JSON only when the Content-Type says so
return new Response(JSON.stringify({ account: null }), {
headers: { 'Content-Type': 'application/json' },
});
}
if (!response.ok) throw new NetworkError(response);
return response;
},
});

To sign out on any other 401 response, add LogoutManager; for token storage, see authentication.

Tests​

  • Replace QueryClientProvider (and the per-test new QueryClient()) in test wrappers with DataProvider, with <Suspense> inside it. Each DataProvider mount starts with an empty store.

  • Helpers that wait for a spinner to disappear fail when the data is already in the store, because then nothing suspends. Wait only when a spinner is present:

    test-utils.ts
    import { screen, waitForElementToBeRemoved } from '@testing-library/react';

    const loadingElements = () => screen.queryAllByTestId(/loading/i);

    export const waitForLoadingToFinish = async () => {
    if (loadingElements().length)
    await waitForElementToBeRemoved(loadingElements);
    };
  • Mock servers (MSW, nock) keep working unchanged. To render from fixtures without a server, use MockResolver.

  • Assertions on query keys or queryClient state go away; assert on what renders.

Check the migration​

  • No file imports @tanstack/react-query, and no queryKey, queryOptions or useQueryClient remains.
  • Every endpoint that returns Entities has a schema.
  • The linter passes, including its import-boundary rules, and no feature folder defines an Entity.
  • Each <Suspense> or AsyncBoundary that catches a useSuspense() is inside DataProvider.
  • The type checker, unit tests and end-to-end tests pass.
  • Opening an item from a freshly loaded list makes no request for that item, when the list returns the full item.
  • After a mutation, every page showing that Entity shows the change without a reload. A test that edits an item on its detail page, then goes back to the list, proves it.