agentleFS
arraydudearraydude/agent-skills/skills/react-query-best-practices/AGENTS.md

agent-skills / react-query-best-practices

AGENTS.md2 starsChanged 3 days agoMITView on GitHub

Version 2.0.0 Rules for @tanstack/react-query v4 and v5, checked against the library source (5.107.1 and 4.44.0), docs and changelog, and based on TkDodo's blog series. Each rule lives in rules/<id>.md with incorrect and correct code. Read the installed version from the lockfile entry for @tanstack/react-query (the package.json range can lie). Then: - Apply the rules whose versions frontmatter includes that major. - Skip a rule whose since is above the installed version. - Inside a rule, use the code block…

  • Installs packages

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

22 rules. About 0 are common, 2 are distinctive, and 20 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 20

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Read the installed version from the lockfile entry for @tanstack/react-query (the package.json range can lie).

    line 12
  2. Very specific:

    Only the v3 package react-query present → these rules don't apply.

    line 19
  3. Distinctive:

    Server state stays in the cache: Keep it out of client-state stores.

    line 28
  4. Very specific:

    Query keys are dependencies: every variable the queryFn reads goes in the key.

    line 30
  5. Very specific:

    Use infiniteQueryOptions for infinite queries.

    line 266
  6. Very specific:

    Every other user of ['todos'] now sees the filtered list.

    line 478
  7. Very specific:

    Use initialData only for complete data you trust: it is persisted to the cache and treated as freshly fetched.

    line 509
  8. Very specific:

    When several components need to show the update, write to the cache instead (mutation-optimistic-updates).

    line 717
  9. Very specific:

    Keep onMutate before onError and onSettled so TypeScript infers the type of onMutateResult (ESLint @tanstack/query/mutation-property-order, …

    line 784
  10. Very specific:

    If the updater returns undefined, setQueryData skips the write and does not create the query.

    line 833
  11. Very specific:

    Prefer typed keys from queryOptions (v5) over annotating the old parameter (see typescript-infer-dont-specify).

    line 835
  12. Very specific:

    Put cache work (invalidation, setQueryData) in the callbacks passed to useMutation, which fire for every mutation.

    line 901
  13. Very specific:

    When mutate runs several times in a row, its per-call callbacks fire only once, for the last call.

    line 947
  14. Very specific:

    Leave refetchOnMount, refetchOnWindowFocus and refetchOnReconnect on.

    line 1128
  15. Very specific:

    Use focusManager.setEventListener / focusManager.setFocused for custom focus sources (e.g.

    line 1167
  16. Very specific:

    When server rendering, create the QueryClient inside your app, never at module scope.

    line 1213
  17. Very specific:

    Avoid useState for the client when there is no <Suspense> boundary between the provider and code that may suspend.

    line 1268
  18. Very specific:

    If a child component needs data from a different query, prefetch it above the <Suspense> boundary with usePrefetchQuery instead (see …

    line 1405
  19. Distinctive:

    Check the Network tab from time to time.

    line 1479
  20. Very specific:

    Use isFetchingNextPage (not isFetching) for the "Loading more..." indicator.

    line 1529
  21. Very specific:

    Use waitFor until the status says the request settled before asserting on data.

    line 1975
  22. Very specific:

    Read server data from the query, not from a useState copy.

    line 2048

≈ “Common” is an estimate: at least 1 in 5 of the 41,581 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md
<!-- Generated by scripts/build-agents-md.py from SKILL.md and rules/. Edit those, then rebuild. -->

React Query Best Practices

Version 2.0.0

Rules for @tanstack/react-query v4 and v5, checked against the library source (5.107.1 and 4.44.0), docs and changelog, and based on TkDodo's blog series. Each rule lives in rules/<id>.md with incorrect and correct code.

Pin the version first

Read the installed version from the lockfile entry for @tanstack/react-query (the package.json range can lie). Then:

  • Apply the rules whose versions frontmatter includes that major.
  • Skip a rule whose since is above the installed version.
  • Inside a rule, use the code block labelled for that version. Unlabelled code is valid for every version the rule lists.
  • Only the v3 package react-query present → these rules don't apply.

To move a repo to the latest v5 (and unlock the skipped rules), run the /react-query-migrate-v5 skill. It applies the migration- and upgrade- rules in order.

Core mental model

  1. React Query is an async state manager, not a fetching library.
  2. Server state stays in the cache. Keep it out of client-state stores.
  3. Stale-while-revalidate: cached data shows at once, refetches run in the background.
  4. Query keys are dependencies: every variable the queryFn reads goes in the key.

Table of Contents

  1. Query Keys & Patterns — CRITICAL
    • 1.1 Query Keys as Dependencies
    • 1.2 Query Key Factory Pattern
    • 1.3 Use queryOptions to Share Query Definitions
    • 1.4 Use queryClient.query() for Imperative Fetching
    • 1.5 Dependent Queries with enabled / skipToken
    • 1.6 status vs fetchStatus
    • 1.7 Status Check Order
    • 1.8 Select Option for Transformations
    • 1.9 Placeholder vs Initial Data
    • 1.10 Tracked Properties
  2. Mutations & Updates — CRITICAL
    • 2.1 Invalidate Queries After Mutations
    • 2.2 Optimistic UI via Mutation Variables
    • 2.3 Optimistic Updates via the Cache
    • 2.4 Update the Cache From Mutation Responses
    • 2.5 Prefer mutate() Over mutateAsync()
    • 2.6 Cache Logic in the Hook, UI Effects at the Call Site
    • 2.7 Read Mutation State Anywhere With useMutationState
    • 2.8 Serialize Dependent Mutations With scope
    • 2.9 Share Mutation Definitions With mutationOptions
  3. Caching Strategy — HIGH
    • 3.1 Setting staleTime
    • 3.2 Refetch Triggers
    • 3.3 staleTime 'static' vs Infinity
  4. SSR & Hydration — HIGH
    • 4.1 Create One QueryClient per Request on the Server
    • 4.2 Prefetch, Dehydrate and Hydrate Instead of initialData
    • 4.3 Set a Default staleTime Above Zero for SSR
  5. Suspense, Prefetching & Infinite Queries — HIGH
    • 5.1 Use useSuspenseQueries for Multiple Suspense Queries
    • 5.2 Flatten Request Waterfalls by Hoisting or Prefetching
    • 5.3 Fetch Infinite Query Pages Safely
  6. WebSocket Integration — HIGH
    • 6.1 Event-Based Invalidation
    • 6.2 staleTime Infinity (Not 'static') for WebSocket-Driven Data
    • 6.3 Invalidate Everything the Socket Owns on Reconnect
  7. TypeScript — MEDIUM
    • 7.1 Type the queryFn, Let TypeScript Infer the Rest
    • 7.2 Validate API Responses at Runtime with Zod
    • 7.3 Register Global Error, Meta and Key Types
  8. Testing — MEDIUM
    • 8.1 Fresh QueryClient Per Test
    • 8.2 Mock the Network, Not useQuery
  9. Tooling — MEDIUM
    • 9.1 Enable the TanStack Query ESLint Plugin
  10. Common Pitfalls — MEDIUM
  • 10.1 Copying Query Data to State
  • 10.2 Fetch Not Rejecting on Errors
  1. Migration v4 → v5 — HIGH
  • 11.1 Single Object Signature Required
  • 11.2 Status "loading" Renamed to "pending
  • 11.3 cacheTime Renamed to gcTime
  • 11.4 useErrorBoundary Renamed to throwOnError
  • 11.5 keepPreviousData Replaced by placeholderData Function
  • 11.6 Query Callbacks Removed from useQuery
  • 11.7 New Dedicated Suspense Hooks
  • 11.8 Hydrate Component Renamed to HydrationBoundary
  • 11.9 initialPageParam Required for Infinite Queries
  • 11.10 refetchPage Replaced by maxPages
  • 11.11 Error Is the Default Error Type in v5
  • 11.12 remove() Method Removed from useQuery
  • 11.13 refetchInterval Callback Signature Changed
  • 11.14 Custom context and contextSharing Replaced by a queryClient Argument
  • 11.15 dehydrate Boolean Options Replaced by Predicates
  • 11.16 Misc v5 Breaking Changes
  1. Upgrading within v5 — HIGH
  • 12.1 Drop Trailing undefined from Partial Key Filters
  • 12.2 Replace Experimental APIs Removed in v5 Minors
  • 12.3 Use onMutateResult and the Mutation Function Context
  • 12.4 Move Off APIs Deprecated or Narrowed in v5 Minors
  • 12.5 Keep TypeScript and React Within the Supported Range

1. Query Keys & Patterns

Impact: CRITICAL

1.1 Query Keys as Dependencies

Impact: CRITICAL (prevents cache collisions and data shown for the wrong parameters) · Versions: v4, v5

Put every variable the queryFn reads, and that can change, into the queryKey. The key is the cache identity and acts like a dependency array. Each distinct value gets its own cache entry, and changing a value switches to that entry and refetches it, subject to staleTime.

Incorrect (filters missing from the key):

const [filters, setFilters] = useState({ status: 'active' });

useQuery({
  queryKey: ['todos'], // every filter state shares one cache entry
  queryFn: () => fetchTodos(filters),
});

Changing filters does not change the key, so no new fetch starts. Every filter state reads and overwrites the same cached list.

Correct (all dependencies in the key):

useQuery({
  queryKey: ['todos', filters],
  queryFn: () => fetchTodos(filters),
});

The same applies to query definitions built outside components:

// Incorrect: id is used but not part of the key
const todoQueries = {
  detail: (id: number) => ({ queryKey: ['todo'], queryFn: () => api.getTodo(id) }),
};

// Correct
const todoQueries = {
  detail: (id: number) => ({ queryKey: ['todo', id], queryFn: () => api.getTodo(id) }),
};
  • Keys must be arrays and serializable with JSON.stringify. Object keys are hashed deterministically, so property order inside an object does not matter. Array item order does matter: ['todos', status, page] and ['todos', page, status] are different keys.
  • Function call targets are not dependencies: fetchTodoById(todoId) needs todoId in the key, not fetchTodoById.
  • Let the linter enforce this: @tanstack/query/exhaustive-deps is part of the plugin's recommended config. Use allowlist.variables / allowlist.types (eslint-plugin-query 5.95+, not in the v4 plugin) for stable clients or config objects (see tooling-eslint-plugin).
  • Centralize keys with a factory (query-key-factory) or queryOptions (query-options-helper, v5) so the key and the queryFn cannot drift apart.

Reference: Query Keys · exhaustive-deps · v4 Query Keys

1.2 Query Key Factory Pattern

Impact: HIGH (consistent keys and invalidation at any level of the hierarchy) · Versions: v4, v5

Build every key for a feature from one factory, ordered from generic to specific. Then partial-key filters can target all queries, all lists, or a single item. In v5, have the factory return queryOptions so each key always travels with its queryFn.

Incorrect (keys typed by hand in each place):

useQuery({ queryKey: ['todos', 'list', filters], queryFn: () => fetchTodos(filters) });
useQuery({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) }); // 'todo' ≠ 'todos'
queryClient.invalidateQueries({ queryKey: ['todos'] }); // misses ['todo', id]

Correct (v5, factory returns queryOptions):

import { queryOptions } from '@tanstack/react-query';

export const todoQueries = {
  all: () => ['todos'] as const,
  lists: () => [...todoQueries.all(), 'list'] as const,
  list: (filters: Filters) =>
    queryOptions({
      queryKey: [...todoQueries.lists(), filters],
      queryFn: () => fetchTodos(filters),
    }),
  detail: (id: number) =>
    queryOptions({
      queryKey: [...todoQueries.all(), 'detail', id],
      queryFn: () => fetchTodo(id),
    }),
};

useQuery(todoQueries.detail(id));
queryClient.invalidateQueries({ queryKey: todoQueries.all() });          // everything
queryClient.invalidateQueries({ queryKey: todoQueries.lists() });        // all lists
queryClient.invalidateQueries({ queryKey: todoQueries.detail(5).queryKey }); // one todo

Correct (v4, plain key factory; queryOptions does not exist in v4):

export const todoKeys = {
  all: ['todos'] as const,
  lists: () => [...todoKeys.all, 'list'] as const,
  list: (filters: Filters) => [...todoKeys.lists(), filters] as const,
  detail: (id: number) => [...todoKeys.all, 'detail', id] as const,
};

useQuery({ queryKey: todoKeys.detail(id), queryFn: () => fetchTodo(id) });
queryClient.invalidateQueries({ queryKey: todoKeys.lists() });
  • Since 5.103 (#11502), a partial filter with trailing undefined items no longer matches shorter keys: { queryKey: ['todos', undefined] } does not match ['todos']. Build the filter without the trailing undefined (e.g. id == null ? todoQueries.all() : todoQueries.detail(id).queryKey).
  • The v5 ESLint rule prefer-query-options (in recommended-strict) flags inline queryKey/queryFn objects passed to query hooks and inline array keys in QueryClient methods and filters. It is syntactic: it fires whether or not a factory exists.
  • v5.64+ lets you constrain every key's shape app-wide by registering a queryKey type on Register (TypeScript guide).

Reference: Query Keys · Query Options · Filters · v4 Query Keys

1.3 Use queryOptions to Share Query Definitions

Impact: HIGH (one key + fn definition reused by hooks, prefetching and cache reads) · Versions: v5 · Since: 5.0

Define each query once with queryOptions and pass the result everywhere: useQuery, useSuspenseQuery, useQueries, queryClient.query and cache helpers. Keeping the key and the queryFn together prevents one key from being used with two different functions. The returned queryKey also carries the data type, so getQueryData and setQueryData are typed without generics.

Incorrect (key and fn repeated; cache reads untyped):

function useGroup(id: number) {
  return useQuery({ queryKey: ['groups', id], queryFn: () => fetchGroup(id) });
}

// elsewhere: a different key, and data is unknown
const cached = queryClient.getQueryData(['group', id]);

Correct:

import { queryOptions, useQueries, useQuery } from '@tanstack/react-query';

export function groupOptions(id: number) {
  return queryOptions({
    queryKey: ['groups', id],
    queryFn: () => fetchGroup(id),
    staleTime: 5 * 1000,
  });
}

useQuery(groupOptions(1));
useQueries({ queries: [groupOptions(1), groupOptions(2)] });
await queryClient.query(groupOptions(23)); // v5.102+, see query-imperative-query-method

const cached = queryClient.getQueryData(groupOptions(42).queryKey);
//    ^? Group | undefined
queryClient.invalidateQueries({ queryKey: groupOptions(42).queryKey });

Override options per component; type inference follows select:

const { data: name } = useQuery({ ...groupOptions(1), select: (group) => group.name });
  • Use infiniteQueryOptions for infinite queries.
  • Type inference via the key does not work for getQueriesData, which returns heterogeneous tuples. Pass the generic explicitly there.
  • ESLint prefer-query-options (in recommended-strict, added in eslint-plugin-query 5.96) enforces this pattern, including reusing .queryKey in QueryClient methods and filters. It does not yet check queryClient.query() / infiniteQuery().
  • v4 has no queryOptions. Use a key factory (query-key-factory) until you migrate (migration-single-signature).

Reference: Query Options · TypeScript: Typing Query Options · prefer-query-options

1.4 Use queryClient.query() for Imperative Fetching

Impact: HIGH (replaces deprecated methods that are removed in v6) · Versions: v5 · Since: 5.102

Since 5.102 (#10658), queryClient.query() and queryClient.infiniteQuery() replace fetchQuery, prefetchQuery, ensureQueryData and their infinite variants. The old methods are deprecated and will be removed in v6. query() returns cached data when it is still fresh per staleTime, otherwise it fetches. It applies select either way and rejects on error.

Incorrect (deprecated in 5.102+):

await queryClient.fetchQuery(todoOptions(id));
await queryClient.prefetchQuery(todoOptions(id));
const todo = await queryClient.ensureQueryData(todoOptions(id));
await queryClient.prefetchInfiniteQuery(feedOptions());

Correct:

import { noop } from '@tanstack/react-query';

// fetchQuery → query
const todo = await queryClient.query(todoOptions(id));

// prefetchQuery → query + swallow the error
await queryClient.query(todoOptions(id)).catch(noop);

// ensureQueryData → query with staleTime: 'static' (any cached data is used as-is)
const cached = await queryClient.query({ ...todoOptions(id), staleTime: 'static' });

// fetchInfiniteQuery / prefetchInfiniteQuery / ensureInfiniteQueryData
await queryClient.infiniteQuery(feedOptions()).catch(noop);
await queryClient.infiniteQuery({ ...feedOptions(), staleTime: 'static' });
  • query() defaults to retry: false unless you configure retries, because no component is there to retry through a re-render. Set retry explicitly for loaders that should retry.
  • Observer-only options are not accepted: enabled, refetchInterval, refetchIntervalInBackground, refetchOn*, retryOnMount, notifyOnChangeProps, throwOnError, suspense, placeholderData.
  • usePrefetchQuery / usePrefetchInfiniteQuery use the new methods internally since 5.102 (#10668).
  • On v4 or v5 before 5.102, keep fetchQuery / prefetchQuery / ensureQueryData. In v4, call them with the object signature so the later rename is mechanical (migration-single-signature).

Reference: Migrating to v5: Imperative QueryClient methods · QueryClient.query

1.5 Dependent Queries with enabled / skipToken

Impact: HIGH (prevents fetches with undefined parameters) · Versions: v4, v5

When a query needs a value that isn't available yet, such as the result of another query or user input, disable it until the value exists. In v5 with TypeScript, prefer skipToken: it disables the query and narrows the parameter, so no non-null assertion is needed.

Incorrect (fires immediately with undefined):

const { data: user } = useQuery({ queryKey: ['user', email], queryFn: () => getUser(email) });

const { data: projects } = useQuery({
  queryKey: ['projects', user?.id],
  queryFn: () => fetchProjects(user?.id), // called with undefined
});

Correct (v5, skipToken, since 5.25):

import { skipToken, useQuery } from '@tanstack/react-query';

const userId = user?.id;
const { data: projects } = useQuery({
  queryKey: ['projects', userId],
  queryFn: userId ? () => fetchProjects(userId) : skipToken,
});

Correct (v4 and v5, enabled):

const userId = user?.id;
const { data: projects } = useQuery({
  queryKey: ['projects', userId],
  queryFn: () => fetchProjects(userId!),
  enabled: !!userId,
});
  • Calling refetch() on a query disabled with skipToken puts the query into an error state ("Missing queryFn"); the returned promise still resolves. If the query must also be triggered manually, use enabled: false.
  • A disabled query with no cached data sits in pending (v4: loading) with fetchStatus: 'idle', so don't show a spinner from that alone. Use isLoading in v5 (isPending && isFetching) or isInitialLoading in v4 (see query-status-vs-fetch-status).
  • v5.48+: enabled also accepts (query) => boolean. v5.83+: the result exposes isEnabled.
  • A disabled query also ignores invalidateQueries / refetchQueries calls.
  • Dependent queries are request waterfalls. If you can, add an endpoint that takes the first input directly (e.g. projects by email).

Reference: Dependent Queries · Disabling Queries · v4 Dependent Queries

1.6 status vs fetchStatus

Impact: MEDIUM (correct spinners for disabled, offline and background-refetching queries) · Versions: v4, v5

status describes the data: is there any? fetchStatus describes the queryFn: is it running (fetching), waiting for a network connection (paused), or doing nothing (idle)? All combinations occur. A query can have no data yet without fetching, for example when it is disabled or offline. A query with data can also be refetching in the background. Choose the flag that matches the UI you are drawing.

Incorrect (v5: spinner from isPending alone):

const { isPending, data } = useQuery({ queryKey: ['todos', filter], queryFn: () => fetchTodos(filter), enabled: !!filter });
if (isPending) return <Spinner />; // spins forever while disabled, or while offline (paused)

Correct (v5):

const { isLoading, isFetching, isPaused, data } = useQuery({
  queryKey: ['todos', filter],
  queryFn: () => fetchTodos(filter),
  enabled: !!filter,
});

if (isLoading) return <Spinner />;             // first fetch in flight (isPending && isFetching)
if (isPaused && !data) return <OfflineNotice />;
if (!data) return <EmptyFilterPrompt />;
return <List items={data} refreshing={isFetching} />; // background refetch indicator

Correct (v4; status: 'loading' is v5's pending, isInitialLoading is v5's isLoading):

const { isInitialLoading, isFetching, data } = useQuery({
  queryKey: ['todos', filter],
  queryFn: () => fetchTodos(filter),
  enabled: !!filter,
});

if (isInitialLoading) return <Spinner />;
  • isRefetching is isFetching && !isPending (v5), i.e. a background refetch.
  • For an app-wide "something is loading" indicator, use useIsFetching().
  • With the default networkMode: 'online', a query that mounts without a connection is pending + paused, not fetching. If online/offline events are unreliable (Electron, some WebViews), consider networkMode: 'always'.
  • v5 deprecates isInitialLoading and will remove it in the next major (see migration-status-pending).

Reference: Queries: FetchStatus · Network Mode · Background Fetching Indicators · v4 Queries

1.7 Status Check Order

Impact: MEDIUM (correct loading/error/data rendering and TypeScript narrowing) · Versions: v4, v5

For most queries, the docs' default order is fine: check the "no data yet" state, then the error, then render data. TypeScript narrows data to defined after both checks. Use data-first ordering only when a background refetch error should leave the cached data on screen.

Incorrect (renders data without handling the states before it):

const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
return <List items={data} />; // data is undefined while pending or after a failed first fetch

Correct (v5, default order):

const { isPending, isError, data, error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

if (isPending) return <Skeleton />;
if (isError) return <ErrorView message={error.message} />;
return <List items={data} />; // narrowed: data is defined

Correct (v4, default order; v4 calls the no-data state isLoading):

const { isLoading, isError, data, error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

if (isLoading) return <Skeleton />;
if (isError) return <ErrorView error={error} />; // v4 types error as unknown by default
return <List items={data} />;

Alternative (data first, keep cached data visible when a refetch fails):

// v5 names; in v4 use isLoading instead of isPending, and narrow error (it is unknown):
// error instanceof Error ? error.message : 'Error'
const { data, error, isPending } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

if (data !== undefined) return <List items={data} stale={!!error} />;
if (error) return <ErrorView message={error.message} />;
if (isPending) return <Skeleton />;
  • A query whose refetch fails keeps its previous data and moves to status: 'error', so with the default order the error branch hides that data.
  • Compare against undefined, not truthiness: 0, '' and false are valid data.
  • isPending (v5) / isLoading (v4) means "no data yet", not "fetching". A disabled or offline query can stay in it without fetching (see query-status-vs-fetch-status).

Reference: Queries · Status Checks (TkDodo) · v4 Queries

1.8 Select Option for Transformations

Impact: MEDIUM (per-component views of one cache entry with fewer re-renders) · Versions: v4, v5

Use select to derive what a component needs from the cached data. select changes only the returned data, never what is stored in the cache, so many components can share one cache entry and each subscribe to its own slice. A component that selects a slice re-renders only when that slice changes.

Incorrect (component-specific view baked into the queryFn):

useQuery({
  queryKey: ['todos'],
  queryFn: async () => {
    const todos = await fetchTodos();
    return todos.filter((todo) => !todo.done); // the cache now holds only open todos
  },
});

Every other user of ['todos'] now sees the filtered list.

Correct (cache raw data, select per component):

const selectOpen = (data: Todo[]) => data.filter((todo) => !todo.done);
const selectCount = (data: Todo[]) => data.length;

export const useTodos = <T = Todo[]>(select?: (data: Todo[]) => T) =>
  useQuery({ queryKey: ['todos'], queryFn: fetchTodos, select });

const openTodos = useTodos(selectOpen);
const count = useTodos(selectCount); // re-renders only when the length changes

In v5, override select per component on top of a shared queryOptions definition. Type inference follows select:

const { data: groupName } = useQuery({ ...groupOptions(1), select: (data) => data.groupName });
  • select re-runs only when data changes or the select function reference changes. An inline arrow therefore runs on every render. Hoist it to module scope, or wrap it in useCallback when it closes over props.
  • select runs on data that is already cached, so it is not the place to signal errors. Validate in the queryFn if bad data should fail the query. A throwing select moves only this observer's result to status: 'error', keeping the last selected data; the cache entry stays success. Since v5.102 (#11011, #11161), a throwing select also resets isPlaceholderData, and since v5.107 (#12540) repeated identical select errors no longer cause render loops.
  • In useQueries, an inline select cannot infer its argument type and falls back to unknown. Annotate it, or put select inside the queryOptions(...) call (v5). Spreading queryOptions and adding select next to it still infers unknown.

Reference: Render Optimizations · Query Options · v4 useQuery: select

1.9 Placeholder vs Initial Data

Impact: MEDIUM (wrong choice persists partial data to the cache or causes needless loading states) · Versions: v4, v5

Use initialData only for complete data you trust: it is persisted to the cache and treated as freshly fetched. Use placeholderData for partial or fake data: it is shown while the real data loads and never written to the cache.

AspectinitialDataplaceholderData
Written to cacheYesNo
FreshnessTreated as fetched now (or at initialDataUpdatedAt), so staleTime appliesOnly shown while the cache is empty; never counts as cached data, so it never prevents the fetch
Result flagnoneisPlaceholderData: true

Incorrect (partial preview data persisted as if complete):

useQuery({
  queryKey: ['blogPost', id],
  queryFn: () => fetchPost(id),
  // list items only have title + snippet, but this is now "the" cached post
  initialData: () => queryClient.getQueryData<Post[]>(['blogPosts'])?.find((p) => p.id === id),
});

Correct (partial data as placeholder, complete data as initial with its real timestamp):

useQuery({
  queryKey: ['blogPost', id],
  queryFn: () => fetchPost(id),
  placeholderData: () => queryClient.getQueryData<Post[]>(['blogPosts'])?.find((p) => p.id === id),
});

useQuery({
  queryKey: ['todo', todoId],
  queryFn: () => fetchTodo(todoId),
  initialData: () => queryClient.getQueryData<Todo[]>(['todos'])?.find((t) => t.id === todoId),
  initialDataUpdatedAt: () => queryClient.getQueryState(['todos'])?.dataUpdatedAt,
});

Correct (v5): keep the previous page visible while the next one loads

import { keepPreviousData, useQuery } from '@tanstack/react-query';

const { data, isPlaceholderData } = useQuery({
  queryKey: ['projects', page],
  queryFn: () => fetchProjects(page),
  placeholderData: keepPreviousData, // or (previousData) => previousData
});
// disable "Next" while isPlaceholderData is true

Correct (v4):

const { data, isPreviousData } = useQuery({
  queryKey: ['projects', page],
  queryFn: () => fetchProjects(page),
  keepPreviousData: true,
});
  • A query with placeholder data reports status: 'success'. In v5.65+, isPlaceholderData: true also narrows the result type.
  • v5 suspense hooks have no placeholderData: wrap key changes in startTransition instead.
  • Infinite queries: initialData and placeholderData must have the { pages, pageParams } shape.

Reference: Placeholder Query Data, Initial Query Data, Paginated Queries, v4 Paginated Queries

1.10 Tracked Properties

Impact: LOW (avoids re-renders from fields the component never reads) · Versions: v4, v5

The query result records which fields you read (a Proxy in v5, property getters in v4). The component re-renders only when one of those fields changes. Read only the fields you need, and never use object rest on the result.

Incorrect (rest destructuring subscribes to every field):

const useTodos = () => {
  const { data: todos, ...rest } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
  return { todos, ...rest }; // re-renders on every isFetching / isStale change
};

Correct (destructure, or return the result object as-is):

const { data, isError } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

// or keep the proxy intact and let the caller read what it needs
const useTodos = () => useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

The result object itself is a new reference on every render; its fields keep their identity until they change. Put the fields you use in hook dependency arrays, not the whole result:

const todosQuery = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

useEffect(() => { /* ... */ }, [todosQuery]);      // Incorrect: runs every render
useEffect(() => { /* ... */ }, [todosQuery.data]); // Correct
  • notifyOnChangeProps overrides tracking: set it to a list of fields, or 'all' to turn the optimization off. With a manual list, you are responsible for choosing the fields.
  • The ESLint rules no-rest-destructuring and no-unstable-deps (both in the v5 plugin's recommended config) catch these two mistakes (see tooling-eslint-plugin).

Reference: Render Optimizations · no-rest-destructuring · no-unstable-deps · v4 useQuery: notifyOnChangeProps

2. Mutations & Updates

Impact: CRITICAL

2.1 Invalidate Queries After Mutations

Impact: CRITICAL (every component showing the changed data gets fresh data) · Versions: v4, v5

After a mutation succeeds, call invalidateQueries with the key prefix it affects. This marks every matching query stale, even one with a long staleTime (v5 staleTime: 'static' is the exception), and refetches the ones currently on screen. Return or await the promise so the mutation stays pending until that refetch finishes.

Incorrect (refetching one observer by hand):

const { refetch } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
const mutation = useMutation({
  mutationFn: updateTodo,
  onSuccess: () => refetch(), // misses ['todos', { page: 2 }], details, etc.
});

Correct (invalidate by prefix and await it):

const mutation = useMutation({
  mutationFn: updateTodo,
  onSuccess: async () => {
    // matches ['todos'], ['todos', { page: 1 }], ['todos', 5] ...
    await queryClient.invalidateQueries({ queryKey: ['todos'] });
  },
});

Correct (several keys at once):

onSuccess: () =>
  Promise.all([
    queryClient.invalidateQueries({ queryKey: ['todos'] }),
    queryClient.invalidateQueries({ queryKey: ['reminders'] }),
  ]),

Keep the button disabled until the data is fresh:

// v5
<button disabled={mutation.isPending}>Save</button>
// v4
<button disabled={mutation.isLoading}>Save</button> {/* v4.40+: isPending */}
  • By default only active queries refetch (refetchType: 'active'). Use 'all', 'inactive' or 'none' to change that. Use exact: true or a predicate for narrower matches.
  • The returned promise resolves once the refetch settles. It does not reject on refetch errors unless you pass { throwOnError: true } as the second argument.

Reference: Invalidations from Mutations · Query Invalidation · v4 Invalidations from Mutations

2.2 Optimistic UI via Mutation Variables

Impact: HIGH (instant feedback without writing to the cache or handling rollback) · Versions: v4, v5

When only one component shows the pending change, render it from the mutation's own variables while the mutation is pending, instead of writing it into the cache. Nothing in the cache changes, so there is nothing to roll back: if the mutation fails, the temporary item disappears. Return the invalidation from onSettled so the item stays visible until the refetched list contains the real one.

Incorrect (cache surgery for a single list item):

onMutate: async (text) => {
  await queryClient.cancelQueries({ queryKey: ['todos'] });
  const previous = queryClient.getQueryData(['todos']);
  queryClient.setQueryData(['todos'], (old) => [...(old ?? []), { id: 'tmp', text }]);
  return { previous };
},
// ...plus onError rollback, for one component that shows the item

Correct (v5):

const { mutate, isPending, isError, variables, submittedAt } = useMutation({
  mutationFn: (text: string) => api.addTodo(text),
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});

<ul>
  {todos.map((t) => <li key={t.id}>{t.text}</li>)}
  {isPending && <li key={submittedAt} style={{ opacity: 0.5 }}>{variables}</li>}
  {isError && (
    <li style={{ color: 'red' }}>
      {variables} <button onClick={() => mutate(variables)}>Retry</button>
    </li>
  )}
</ul>

Correct (v4; use isLoading before 4.40):

const { isPending, variables } = useMutation({
  mutationFn: (text: string) => api.addTodo(text),
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});

{isPending && <li style={{ opacity: 0.5 }}>{variables}</li>}
  • variables are kept after an error, so you can offer a retry (v4 types them TVariables | undefined in every status, so pass variables!). v5's submittedAt gives each pending item a stable key.
  • When several components need to show the update, write to the cache instead (mutation-optimistic-updates). When the mutation runs in a different component from the list, use mutation-state-across-components (v5).
  • The v4 docs describe only the cache-based approach, but v4 exposes variables on the result from 4.0 (it is part of the mutation state, set before onMutate runs). submittedAt is v5-only.

Reference: Optimistic Updates: Via the UI · Migrating to v5: Simplified optimistic updates

2.3 Optimistic Updates via the Cache

Impact: HIGH (instant feedback everywhere the data is shown, with rollback) · Versions: v4, v5

When several places on screen show the changed data, write the expected result into the cache in onMutate. Steps: cancel in-flight fetches for that key so they don't overwrite your update, snapshot the old value, return the snapshot, restore it in onError, then invalidate in onSettled. Return the invalidate promise so the mutation stays pending until the refetch finishes. If only one component shows the pending item, the simpler variables approach is enough (see mutation-optimistic-via-variables).

Incorrect (no cancel, no rollback, and the invalidation is not returned):

useMutation({
  mutationFn: updateTodo,
  onMutate: (newTodo) => {
    queryClient.setQueryData(['todos', newTodo.id], newTodo); // an in-flight fetch can overwrite this
  },
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['todos'] }); // not returned: isPending ends too early
  },
});

Correct (v5.89+: onMutate(variables, context) and onError(error, variables, onMutateResult, context)):

useMutation({
  mutationFn: updateTodo,
  onMutate: async (newTodo, context) => {
    await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] });
    const previousTodo = context.client.getQueryData(['todos', newTodo.id]);
    context.client.setQueryData(['todos', newTodo.id], newTodo);
    return { previousTodo }; // becomes `onMutateResult`
  },
  onError: (err, newTodo, onMutateResult, context) => {
    context.client.setQueryData(['todos', newTodo.id], onMutateResult?.previousTodo);
  },
  onSettled: (data, error, newTodo, onMutateResult, context) =>
    context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] }),
});

Correct (v4, and v5 before 5.89: the third argument, context, is what onMutate returned):

const queryClient = useQueryClient();
useMutation({
  mutationFn: updateTodo,
  onMutate: async (newTodo) => {
    await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] });
    const previousTodo = queryClient.getQueryData(['todos', newTodo.id]);
    queryClient.setQueryData(['todos', newTodo.id], newTodo);
    return { previousTodo };
  },
  onError: (err, newTodo, context) => {
    queryClient.setQueryData(['todos', newTodo.id], context?.previousTodo);
  },
  onSettled: (data, error, newTodo) =>
    queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] }),
});
  • In 5.89 the argument that holds onMutate's return value was renamed onMutateResult. The final argument context is now { client, meta, mutationKey }. The arguments are positional, so v4-style code still runs. Rename the parameters anyway, so that context means the same thing everywhere.
  • Using queryClient from useQueryClient() is still valid in v5. context.client matters when the options are defined outside a component (mutationOptions, setMutationDefaults).
  • In most failure cases, refetching alone reverts the optimistic state. Rollback covers the cases where that refetch cannot succeed.
  • Keep onMutate before onError and onSettled so TypeScript infers the type of onMutateResult (ESLint @tanstack/query/mutation-property-order, since 5.78).

Reference: Optimistic Updates · v4 Optimistic Updates

2.4 Update the Cache From Mutation Responses

Impact: MEDIUM (instant UI update without an extra request) · Versions: v4, v5

When the mutation returns the updated object, write it to the cache with setQueryData instead of refetching data you already have. The updater can receive undefined when nothing is cached under that key. Handle that case, and always return new objects instead of mutating the old ones.

Incorrect (crashes on an empty cache, and mutates in place):

onSuccess: (updated) => {
  queryClient.setQueryData(['todos', 'list'], (old: Todo[]) =>
    old.map((t) => (t.id === updated.id ? updated : t)), // old may be undefined
  );
  queryClient.setQueryData(['todos', 'detail', updated.id], (old) => {
    old.title = updated.title; // in-place mutation: subtle bugs
    return old;
  });
},

Correct (handles undefined and stays immutable):

const mutation = useMutation({
  mutationFn: updateTodo,
  onSuccess: (updated) => {
    queryClient.setQueryData(['todos', 'detail', updated.id], updated);

    queryClient.setQueryData<Todo[]>(['todos', 'list'], (old) =>
      old ? old.map((t) => (t.id === updated.id ? updated : t)) : old,
    );
  },
});

Combined with invalidation (patch what you know, refetch the rest):

onSuccess: (updated) => {
  queryClient.setQueryData(['todos', 'detail', updated.id], updated);
  // sorted or filtered lists may change order: let the server decide
  return queryClient.invalidateQueries({ queryKey: ['todos', 'list'] });
},
  • If the updater returns undefined, setQueryData skips the write and does not create the query.
  • To patch every list variant at once (filters, pages), use queryClient.setQueriesData({ queryKey: ['todos', 'list'] }, updater).
  • Prefer typed keys from queryOptions (v5) over annotating the old parameter (see typescript-infer-dont-specify).

Reference: Updates from Mutation Responses · QueryClient.setQueryData · v4 Updates from Mutation Responses

2.5 Prefer mutate() Over mutateAsync()

Impact: HIGH (no unhandled promise rejections from fire-and-forget calls) · Versions: v4, v5

Call mutate() and handle the outcome with callbacks. mutateAsync() returns a promise that rejects when the mutation fails. Use it only when you need that promise: to compose steps that depend on each other, or to wait for several parallel calls. Always wrap it in try/catch.

Incorrect (promise rejection that nothing handles):

const { mutateAsync } = useMutation({ mutationFn: updateTodo });

const handleSave = () => {
  mutateAsync(todo); // rejects on error and nothing catches it
};

Correct (mutate with callbacks):

const { mutate } = useMutation({
  mutationFn: updateTodo,
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});

mutate(todo, {
  onSuccess: () => toast.success('Saved!'),
  onError: (error) => toast.error(error instanceof Error ? error.message : 'Save failed'), // v4 types error as unknown
});

Correct (mutateAsync when one step needs the previous result):

async function handleCreate() {
  try {
    const user = await createUser.mutateAsync(userData);
    await createProfile.mutateAsync({ userId: user.id, ...profileData });
  } catch (error) {
    toast.error('Failed to create user');
  }
}

Correct (mutateAsync for parallel calls):

// Callbacks passed per call to mutate() fire only for the LAST call,
// so use one promise per call and wait for all of them.
const results = await Promise.allSettled(
  todos.map((todo) => addTodo.mutateAsync(todo)),
);
  • Callbacks passed per call to mutate run only once, for the latest call, and only if the component is still mounted. Callbacks passed to useMutation run for every call.
  • v5: if the calls only need to run one after another rather than feed into each other, use a mutation scope instead (see mutation-scope-serial).

Reference: Mutations · useMutation · v4 Mutations

2.6 Cache Logic in the Hook, UI Effects at the Call Site

Impact: MEDIUM (cache stays consistent even if the component unmounts) · Versions: v4, v5

Put cache work (invalidation, setQueryData) in the callbacks passed to useMutation, which fire for every mutation. Put UI effects (toasts, navigation, closing a modal) in the callbacks passed to mutate(). Those fire only for the latest call, and only while the component is still mounted.

Incorrect (cache update tied to the component):

function TodoEditor() {
  const { mutate } = useMutation({ mutationFn: updateTodo });
  mutate(todo, {
    // skipped if the user navigates away before the request settles
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
  });
}

Correct (custom hook owns the cache logic):

export function useUpdateTodo() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: updateTodo,
    onSuccess: (data) => {
      queryClient.setQueryData(['todos', 'detail', data.id], data);
      return queryClient.invalidateQueries({ queryKey: ['todos', 'list'] });
    },
  });
}

Correct (component owns the UI effects):

function TodoEditor() {
  const { mutate } = useUpdateTodo();
  const handleSave = () =>
    mutate(todo, {
      onSuccess: () => {
        toast.success('Saved!');
        closeModal();
      },
      onError: () => toast.error('Save failed'),
    });
}
  • Callbacks passed to useMutation run first, then the ones passed to mutate.
  • When mutate runs several times in a row, its per-call callbacks fire only once, for the last call. Use mutateAsync if you need a result for each call (see mutation-prefer-mutate).
  • v5: to share the hook's options without a wrapper hook, see mutation-options-factory.

Reference: Mutations: Mutation Side Effects · v4 Mutations

2.7 Read Mutation State Anywhere With useMutationState

Impact: MEDIUM (show pending or finished mutations without prop drilling or extra global state) · Versions: v5 · Since: 5.0

When the component that shows pending work is not the one that called useMutation, read that work from the MutationCache with useMutationState. Give the mutation a mutationKey, filter on it, and use select to pull out what you need. The result is an array, because several mutations can be running at the same time.

Incorrect (copying mutation state into global state):

const { mutate } = useMutation({
  mutationFn: addTodo,
  onMutate: (text) => store.setPending((p) => [...p, text]),
  onSettled: (_d, _e, text) => store.setPending((p) => p.filter((t) => t !== text)),
});

Correct (the mutation is the source of truth):

// in the form
const { mutate } = useMutation({
  mutationKey: ['addTodo'],
  mutationFn: (text: string) => api.addTodo(text),
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});

// in the list, anywhere in the tree
const pending = useMutationState<{ text: string; key: number }>({
  filters: { mutationKey: ['addTodo'], status: 'pending' },
  select: (m) => ({ text: m.state.variables as string, key: m.state.submittedAt }),
});

{pending.map((p) => <li key={p.key} style={{ opacity: 0.5 }}>{p.text}</li>)}

Correct (global "saving…" indicator):

const isSaving = useMutationState({ filters: { status: 'pending' } }).length > 0;
// or simply: useIsMutating() > 0
  • Filters accept mutationKey, exact, status and predicate.
  • Define the key once with mutationOptions so the hook and the filter cannot drift apart (see mutation-options-factory).
  • v4 has no useMutationState. Migrate first (migration-single-signature).

Reference: Optimistic Updates · useMutationState · Filters

2.8 Serialize Dependent Mutations With scope

Impact: MEDIUM (prevents out-of-order writes from rapid repeated mutations) · Versions: v5 · Since: 5.31

By default, every mutate() call runs immediately and in parallel, even repeated calls of the same mutation. Requests can then finish in a different order than they were sent. When order matters, for example repeated saves of the same document, give the mutations a shared scope.id. Mutations with the same id run one after another; later ones wait with isPaused: true until their turn.

Incorrect (parallel saves can finish out of order):

const save = useMutation({ mutationFn: saveDraft });
// typing fast: save #2 may resolve before save #1 and get overwritten by it
save.mutate(draftV1);
save.mutate(draftV2);

Correct (one queue per document):

const save = useMutation({
  mutationFn: saveDraft,
  scope: { id: `draft-${draftId}` },
});

save.mutate(draftV1);
save.mutate(draftV2); // onMutate runs now; mutationFn waits paused until draftV1 settles
  • isPaused is true while a mutation waits in its scope queue, and also while it waits for the network to come back. Account for both before showing "offline" UI.
  • Mutations without a scope keep running in parallel. Only mutations that share the exact scope.id are queued together.
  • 5.104.2 fixed a bug where queued scoped mutations did not start while the window was unfocused.
  • v4 has no scope. Migrate first (migration-single-signature).

Reference: Mutations: Mutation Scopes · useMutation

2.9 Share Mutation Definitions With mutationOptions

Impact: MEDIUM (one typed definition reused by hooks, defaults and mutation-state filters) · Versions: v5 · Since: 5.89

Define each mutation once with mutationOptions and pass the result to useMutation. It returns the same object, fully typed. If you include a mutationKey, that overload requires it, so useMutationState filters can reuse the exact key.

Incorrect (key and options duplicated across files):

useMutation({ mutationKey: ['posts', 'create'], mutationFn: createPost });
// elsewhere: typo, so the filter silently never matches
useMutationState({ filters: { mutationKey: ['post', 'create'], status: 'pending' } });

Correct:

import { mutationOptions, useMutation, useMutationState } from '@tanstack/react-query';

export const createPostOptions = mutationOptions({
  mutationKey: ['posts', 'create'],
  mutationFn: createPost,
  onSuccess: (data, variables, onMutateResult, context) =>
    context.client.invalidateQueries({ queryKey: ['posts'] }),
});

function CreatePost() {
  const mutation = useMutation(createPostOptions);
  return <button onClick={() => mutation.mutate({ title: 'Hello' })}>Create</button>;
}

function SavingIndicator() {
  const saving = useMutationState({
    filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
  }).length > 0;
  return saving ? <span>Saving…</span> : null;
}
  • The options live outside any component, so callbacks use context.client (5.89+) instead of useQueryClient().
  • The overload without mutationKey suits mutations you never need to look up by key.
  • mutationOptions itself shipped in 5.82; the context argument used above needs 5.89.
  • v4.44 has a backported mutationOptions without context.client, and v4 has no useMutationState: read the pending state with useIsMutating({ mutationKey }). Older v4: use a custom hook (see mutation-callback-separation).

Reference: mutationOptions · Mutations

3. Caching Strategy

Impact: HIGH

3.1 Setting staleTime

Impact: HIGH (the recommended way to avoid excessive refetches) · Versions: v4, v5

By default staleTime is 0: cached data is stale immediately, so it refetches whenever a new instance mounts, the window regains focus, or the network reconnects. Set staleTime to how long the data stays acceptable. The docs call this the recommended way to cut refetches, rather than turning the triggers off.

Incorrect (default 0 for data that rarely changes, then turning off triggers to compensate):

useQuery({ queryKey: ['config'], queryFn: fetchConfig, refetchOnWindowFocus: false, refetchOnMount: false });

Correct (a global baseline plus per-query overrides):

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 2 * 60 * 1000 } }, // read from cache for 2 min
});

useQuery({ queryKey: ['notifications'], queryFn: fetchNotifications, staleTime: 30 * 1000 });
useQuery({ queryKey: ['config'], queryFn: fetchConfig, staleTime: 30 * 60 * 1000 });
useQuery({ queryKey: ['automations', id], queryFn: () => fetchAutomation(id), staleTime: Infinity }); // invalidated by WebSocket events

Correct (v5.44+, staleTime computed per query):

useQuery({
  queryKey: ['job', id],
  queryFn: () => fetchJob(id),
  staleTime: (query) => (query.state.data?.status === 'done' ? Infinity : 5 * 1000),
});
  • Infinity means the data is never stale until you invalidate it. v5.79+ adds 'static', which also ignores invalidateQueries (see cache-static-vs-infinity). v4 accepts only a number.
  • Garbage collection is a separate setting. Inactive queries are removed after 5 minutes by default: gcTime in v5, cacheTime in v4 (see migration-cache-time-to-gc-time). Don't restate defaults (gcTime 5 min on the client, retry 3 on the client and 0 on the server in v5) in your config.
  • refetchInterval polls regardless of staleTime.

Reference: Important Defaults · Caching · v4 Important Defaults

3.2 Refetch Triggers

Impact: HIGH (keeps data fresh without excess requests) · Versions: v4, v5

Leave refetchOnMount, refetchOnWindowFocus and refetchOnReconnect on. They refetch only stale queries, so staleTime is the setting that controls how often they fire. Disable a trigger only when something else keeps the data fresh.

Incorrect (turning every trigger off to silence refetches):

useQuery({
  queryKey: ['user'],
  queryFn: fetchUser,
  refetchOnMount: false,
  refetchOnWindowFocus: false,
  refetchOnReconnect: false,
}); // staleTime is still 0, but only explicit invalidation refreshes the data

Correct (tune staleTime, keep the triggers):

useQuery({ queryKey: ['user'], queryFn: fetchUser, staleTime: 5 * 60 * 1000 });

// Data pushed over a WebSocket: Infinity alone already stops staleness-based refetches.
// Invalidating marks it stale, after which the triggers apply again.
useQuery({ queryKey: ['automations', id], queryFn: () => fetchAutomation(id), staleTime: Infinity });

Correct ('always' and callback forms):

useQuery({
  queryKey: ['inbox'],
  queryFn: fetchInbox,
  refetchOnWindowFocus: 'always',                                  // refetch even when fresh
  refetchOnMount: (query) => query.state.status === 'error',       // callback receives the query
});
  • These callbacks receive only query (v4 and v5). If you need data, read query.state.data, which has not been through select.
  • staleTime: 'static' (v5.79+) blocks even the 'always' settings.
  • refetchOnReconnect defaults to false under networkMode: 'always'.
  • v5 detects focus only through visibilitychange, not the focus event. If refocusing doesn't refetch in development, turn off Chrome DevTools > Rendering > "Emulate a focused page".
  • Use focusManager.setEventListener / focusManager.setFocused for custom focus sources (e.g. React Native AppState).

Reference: Window Focus Refetching · Important Defaults · v4 Window Focus Refetching

3.3 staleTime 'static' vs Infinity

Impact: MEDIUM (choose whether manual invalidation can still refresh the data) · Versions: v5 · Since: 5.79

Both values stop staleness-based refetches. Use Infinity when the data changes only through your own invalidation, for example WebSocket events or mutations. Use 'static' (since 5.79, #9139) for data that cannot change while the app runs. With 'static', invalidateQueries and refetchQueries skip the query (only while an observer with 'static' is mounted: refetchType: 'inactive' or 'all' still refetches an unobserved one), and refetchOnMount, refetchOnWindowFocus and refetchOnReconnect set to 'always' are blocked as well.

Incorrect ('static' on data that mutations update):

useQuery({ queryKey: ['todos'], queryFn: fetchTodos, staleTime: 'static' });

useMutation({
  mutationFn: addTodo,
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), // ignored by 'static'
});

Correct:

// Changes only when we invalidate it: invalidation still works
useQuery({ queryKey: ['todos'], queryFn: fetchTodos, staleTime: Infinity });

// Fixed for the session: feature flags at boot, permissions at login, reference tables
useQuery({ queryKey: ['feature-flags'], queryFn: fetchFlags, staleTime: 'static' });
  • staleTime can also be a function returning a number or 'static' per query (5.44+).
  • queryClient.query({ ...options, staleTime: 'static' }) is the replacement for ensureQueryData: it returns cached data if any exists (see query-imperative-query-method).
  • 'static' is not garbage-collection protection. Inactive queries are still removed after gcTime.
  • v4 accepts only numbers. Use Infinity there (see cache-stale-time).

Reference: Important Defaults · useQuery: staleTime

4. SSR & Hydration

Impact: HIGH

4.1 Create One QueryClient per Request on the Server

Impact: CRITICAL (a module-level client shares cached data, including private data, between all users) · Versions: v4, v5

When server rendering, create the QueryClient inside your app, never at module scope. A module-level client is shared by every request on the server, so all data goes to all users. That hurts performance and leaks sensitive data. In the browser, reuse a single client.

Incorrect (module scope: shared across requests on the server):

const queryClient = new QueryClient();

export default function MyApp({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <Component {...pageProps} />
    </QueryClientProvider>
  );
}

Correct (v5): new client per server request, singleton in the browser

'use client';
import { environmentManager, QueryClient, QueryClientProvider } from '@tanstack/react-query';

function makeQueryClient() {
  return new QueryClient({ defaultOptions: { queries: { staleTime: 60 * 1000 } } });
}

let browserQueryClient: QueryClient | undefined;

export function getQueryClient() {
  if (environmentManager.isServer()) return makeQueryClient(); // v5 before 5.91: `isServer`
  // Keep one browser client so it is not recreated if React suspends during the first render
  if (!browserQueryClient) browserQueryClient = makeQueryClient();
  return browserQueryClient;
}

export function Providers({ children }: { children: React.ReactNode }) {
  const queryClient = getQueryClient();
  return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}

Correct (v4, and v5 pages-router style setups): client in React state

export default function MyApp({ Component, pageProps }) {
  const [queryClient] = React.useState(() => new QueryClient());
  return (
    <QueryClientProvider client={queryClient}>
      <Component {...pageProps} />
    </QueryClientProvider>
  );
}
  • environmentManager.isServer() was added in 5.91, and the isServer constant is deprecated in its favour.
  • Avoid useState for the client when there is no <Suspense> boundary between the provider and code that may suspend. React throws the client away if the first render suspends.
  • In Server Components, cache(() => new QueryClient()) from react gives one client per request.

Reference: Server Rendering & Hydration, Advanced Server Rendering, v4 SSR

4.2 Prefetch, Dehydrate and Hydrate Instead of initialData

Impact: HIGH (server data reaches every useQuery for that key and refreshes on later navigations) · Versions: v4, v5

To server render, prefetch into a fresh QueryClient in the loader, return dehydrate(queryClient), and wrap the tree in a hydration boundary. Passing loader data as initialData has drawbacks. You must pass it down to every useQuery that needs it. dataUpdatedAt reflects page load, not the server fetch. And initialData never overwrites existing cache data, even when the new data is fresher.

Incorrect (loader data as initialData):

export async function getServerSideProps() {
  return { props: { posts: await getPosts() } };
}
function Posts({ posts }) {
  const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts, initialData: posts });
}

Correct (v5.102+):

import { dehydrate, HydrationBoundary, noop, QueryClient } from '@tanstack/react-query';

export async function getServerSideProps() {
  const queryClient = new QueryClient();
  await Promise.all([
    queryClient.query({ queryKey: ['posts'], queryFn: getPosts }).catch(noop),
    queryClient.query({ queryKey: ['tags'], queryFn: getTags }).catch(noop),
  ]);
  return { props: { dehydratedState: dehydrate(queryClient) } };
}

export default function PostsRoute({ dehydratedState }) {
  return (
    <HydrationBoundary state={dehydratedState}>
      <Posts />
    </HydrationBoundary>
  );
}

In v5 before 5.102, use await queryClient.prefetchQuery({ queryKey, queryFn }). It never throws, so it needs no .catch. In 5.102 prefetchQuery was deprecated in favour of query.

Correct (v4):

import { dehydrate, Hydrate, QueryClient } from '@tanstack/react-query';

export async function getServerSideProps() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery(['posts'], getPosts);
  return { props: { dehydratedState: dehydrate(queryClient) } };
}
// <Hydrate state={dehydratedState}><Posts /></Hydrate>
  • dehydrate includes only successful queries by default, so failed prefetches are retried on the client. For critical data, await queryClient.query(...) without .catch and handle the error yourself (for example with a 404 or 500 response).
  • Queries you don't prefetch are fetched on the client after hydration. Mixing both is fine.
  • With a custom SSR setup, don't embed the state with raw JSON.stringify, which is an XSS risk. Use a serializer that escapes it, such as devalue.
  • Server Components: treat them as a place to prefetch only. Don't render the result of queryClient.query on the server, because it goes out of sync when the client refetches.

Reference: Server Rendering & Hydration, Advanced Server Rendering, v4 SSR

4.3 Set a Default staleTime Above Zero for SSR

Impact: HIGH (avoids refetching every server-rendered query as soon as the page loads) · Versions: v4, v5

Staleness is measured from when the query was fetched on the server. With the default staleTime: 0, every hydrated query is already stale on the client and refetches in the background on page load, so the data is fetched twice. Set a default staleTime above zero on the client used for SSR.

Incorrect (hydrated data refetches immediately on the client):

const [queryClient] = React.useState(() => new QueryClient());

Correct:

const [queryClient] = React.useState(
  () =>
    new QueryClient({
      defaultOptions: {
        queries: {
          // With SSR, set a default staleTime above 0
          // to avoid refetching immediately on the client
          staleTime: 60 * 1000,
        },
      },
    }),
);
  • Prefetches use the client's default staleTime too. Setting it on the server client avoids passing a staleTime to every prefetch call.
  • Stale data refetching on load pairs well with CDN-cached markup: cache the page for a long time and keep the query staleTime low, so data refreshes in the background when a user visits.
  • The server's clock must be correct, because dataUpdatedAt comes from the server (in UTC).

Reference: Server Rendering & Hydration, v4 SSR

5. Suspense, Prefetching & Infinite Queries

Impact: HIGH

5.1 Use useSuspenseQueries for Multiple Suspense Queries

Impact: HIGH (several useSuspenseQuery calls in one component fetch one after another) · Versions: v5

Each useSuspenseQuery suspends the component until it resolves, so the next call in the same component doesn't start fetching until the previous one finishes. With regular useQuery these would run in parallel. When a component needs more than one suspense query, put them all in one useSuspenseQueries call.

Incorrect (three serial requests):

function App() {
  const users = useSuspenseQuery({ queryKey: ['users'], queryFn: fetchUsers });
  const teams = useSuspenseQuery({ queryKey: ['teams'], queryFn: fetchTeams });
  const projects = useSuspenseQuery({ queryKey: ['projects'], queryFn: fetchProjects });
  // nothing renders until all three have finished, one after another
}

Correct (fetched in parallel):

function App() {
  const [users, teams, projects] = useSuspenseQueries({
    queries: [
      { queryKey: ['users'], queryFn: fetchUsers },
      { queryKey: ['teams'], queryFn: fetchTeams },
      { queryKey: ['projects'], queryFn: fetchProjects },
    ],
  });
}
  • If a child component needs data from a different query, prefetch it above the <Suspense> boundary with usePrefetchQuery instead (see prefetch-flatten-waterfalls).
  • Queries inside useSuspenseQueries can't use enabled, placeholderData or throwOnError, the same as useSuspenseQuery.
  • Serial fetching is what you want for dependent queries, because suspense queries in one component run in order.

v4.39+ also exports useSuspenseQueries, and this code compiles there. Older v4: see migration-suspense-hooks for moving off suspense: true.

Reference: Performance & Request Waterfalls, useSuspenseQueries

5.2 Flatten Request Waterfalls by Hoisting or Prefetching

Impact: HIGH (each nested query that waits on its parent adds a full network round trip) · Versions: v4, v5

A child that only renders after its parent's query resolves cannot start its own query until then, so the requests run one after another. Start independent queries together: hoist the child's query into the parent, or prefetch it there.

Incorrect (comments wait for the article):

function Article({ id }) {
  const article = useQuery({ queryKey: ['article', id], queryFn: getArticleById });
  if (!article.data) return 'Loading article...';
  return <Comments id={id} />; // its useQuery starts only now
}

Correct (start the child's query in the parent and ignore the result):

function Article({ id }) {
  const article = useQuery({ queryKey: ['article', id], queryFn: getArticleById });
  // Prefetch; notifyOnChangeProps: [] avoids rerenders from this observer
  useQuery({
    queryKey: ['article-comments', id],
    queryFn: getArticleCommentsById,
    notifyOnChangeProps: [],
  });
  if (!article.data) return 'Loading article...';
  return <Comments id={id} />;
}

Correct (with Suspense, v5.47+ or v4.43+): prefetch above the boundary

function ArticleLayout({ id }) {
  usePrefetchQuery({ queryKey: ['article-comments', id], queryFn: getArticleCommentsById });
  return (
    <Suspense fallback="Loading article">
      <Article id={id} /> {/* uses useSuspenseQuery */}
    </Suspense>
  );
}

A plain useQuery prefetch does not work with Suspense: it would start only after the suspending query resolves.

Correct (v5.102+): dependent data you can't hoist, prefetched from the parent's queryFn

queryFn: async (...args) => {
  const feed = await getFeed(...args);
  for (const item of feed) {
    if (item.type === 'GRAPH') {
      void queryClient.query({ queryKey: ['graph', item.id], queryFn: getGraphDataById }).catch(noop);
    }
  }
  return feed;
},

Correct (v4 and v5 before 5.102): the same code with void queryClient.prefetchQuery({ queryKey: ['graph', item.id], queryFn: getGraphDataById }). prefetchQuery never throws.

  • A truly dependent query (one that needs the parent's result) can't be flattened by prefetching. Return both from one API endpoint, or move the waterfall to the server.
  • Code splitting adds waterfalls (load JS, then fetch). Prefetching in the parent loads the code and the data in parallel.
  • Router loaders are the most systematic option. Prefetch non-critical data without await, and await critical data so errors reach the route's error boundary.
  • Check the Network tab from time to time. Waterfalls creep in when queries are added to parents or children.

Reference: Performance & Request Waterfalls, Prefetching & Router Integration, v4 Prefetching

5.3 Fetch Infinite Query Pages Safely

Impact: HIGH (a page fetch silently cancels the fetch already running on the single shared cache entry) · Versions: v4, v5

All pages of an infinite query share one cache entry, and only one fetch can run at a time. Calling fetchNextPage while a fetch is in progress cancels that fetch, a background refresh included. Guard automatic triggers such as scroll handlers with hasNextPage && !isFetching, and derive page params from getNextPageParam.

Incorrect (fires on every scroll event, even mid-refetch):

<List onEndReached={() => fetchNextPage()} />

Correct (v5):

const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam }) => fetchProjects(pageParam),
  initialPageParam: 0,
  getNextPageParam: (lastPage) => lastPage.nextCursor, // undefined or null = no more pages
});

<List onEndReached={() => hasNextPage && !isFetching && fetchNextPage()} />;

Correct (v4):

const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam = 0 }) => fetchProjects(pageParam),
  getNextPageParam: (lastPage) => lastPage.nextCursor, // undefined, null or false = no more pages
});

<List onEndReached={() => hasNextPage && !isFetching && fetchNextPage()} />;

Keep pages and pageParams aligned when editing the cache:

queryClient.setQueryData<InfiniteData<Page>>(['projects'], (data) => data && ({
  pages: data.pages.slice(1),
  pageParams: data.pageParams.slice(1),
}));
  • Use isFetchingNextPage (not isFetching) for the "Loading more..." indicator. isFetching is also true during background refetches.
  • On refetch, pages are refetched one after another starting from the first, so cursors are never stale. Many pages means many requests: in v5 limit them with maxPages. Add getPreviousPageParam too, so users can scroll back to the pages maxPages dropped.
  • v5 ESLint @tanstack/query/infinite-query-property-order (recommended, auto-fixable) requires queryFn before getPreviousPageParam / getNextPageParam, for type inference.
  • fetchNextPage defaults to cancelRefetch: true: it cancels an in-flight fetch and starts the page fetch. With cancelRefetch: false, calls made while a fetch runs are ignored and reuse that fetch.

Reference: Infinite Queries, v4 Infinite Queries

6. WebSocket Integration

Impact: HIGH

6.1 Event-Based Invalidation

Impact: HIGH (simple, predictable real-time sync) · Versions: v4, v5

Have the backend push small events that name what changed, not full data objects. The client then calls invalidateQueries for that key. Queries on screen refetch in the background, and the rest are marked stale for their next mount. This follows the docs' approach of targeted invalidation plus background refetching, and avoids maintaining a normalized client cache.

Incorrect (pushing full payloads and merging them by hand):

socket.on('todo', (todo) => {
  // every list, filter and page variant now needs custom merge logic
  queryClient.setQueryData(['todos', 'list'], (old) => [...old, todo]);
});

Correct (events carry query keys):

// Backend sends: { "entity": ["automations", "list"] }
//                { "entity": ["automations", "detail", "abc123"] }
function useWebSocketSync() {
  const queryClient = useQueryClient();

  useEffect(() => {
    const socket = connectWebSocket();
    socket.on('invalidate', (event) => {
      queryClient.invalidateQueries({ queryKey: event.entity });
    });
    return () => socket.disconnect();
  }, [queryClient]);
}

Correct (patch high-frequency fields, invalidate the rest):

switch (message.type) {
  case 'AUTOMATION_STATUS_CHANGED':
    // frequent and small: patch it, and leave the cache alone when nothing is cached
    queryClient.setQueryData(['automations', 'detail', message.id], (old) =>
      old ? { ...old, status: message.status } : old,
    );
    break;
  case 'AUTOMATION_UPDATED':
    queryClient.invalidateQueries({ queryKey: ['automations'] });
    break;
}
  • Prefix matching means ['automations'] also invalidates lists and details. Use exact: true to target a single key.
  • Pair this rule with websocket-stale-time-infinity and websocket-reconnection.

Reference: Query Invalidation · v4 Query Invalidation

6.2 staleTime Infinity (Not 'static') for WebSocket-Driven Data

Impact: HIGH (no redundant refetches, while socket invalidations still work) · Versions: v4, v5

When a socket tells you what changed, set staleTime: Infinity. The data then stays fresh until an event invalidates it, so mounting, window focus and network reconnect no longer trigger refetches. Do not use v5's staleTime: 'static' here: invalidateQueries has no effect on static queries, so socket events would do nothing.

Incorrect (v5: 'static' ignores invalidation):

useQuery({
  queryKey: ['automations', 'detail', id],
  queryFn: () => fetchAutomation(id),
  staleTime: 'static', // invalidateQueries() from the socket is ignored
});

Correct (Infinity: fresh until invalidated):

useQuery({
  queryKey: ['automations', 'detail', id],
  queryFn: () => fetchAutomation(id),
  staleTime: Infinity,
});

Correct (app-wide, when the socket covers everything):

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: Infinity } },
});
  • refetchOnWindowFocus: false is unnecessary with Infinity, because focus refetches only run for stale data.
  • 'static' (added in 5.79) is for data that cannot change while the app runs, such as feature flags or permissions loaded at login. It also blocks refetchOn*: 'always'.
  • With Infinity, the automatic refetch on reconnect is skipped too, so handle socket reconnects yourself (see websocket-reconnection).

Reference: Important Defaults · Window Focus Refetching · v4 Important Defaults

6.3 Invalidate Everything the Socket Owns on Reconnect

Impact: MEDIUM (recovers events missed while disconnected) · Versions: v4, v5

While the socket is down, events are lost and nothing gets marked invalidated. On reconnect, invalidate every key the socket manages, or the whole cache. Do not filter on query.state.isInvalidated: that flag resets on every successful fetch, and invalidated queries that are on screen have already refetched. That filter therefore matches mostly inactive queries (plus disabled ones and those whose last fetch failed), which the default refetchType: 'active' does not refetch, so the handler does almost nothing.

Incorrect (matches almost nothing):

socket.on('connect', () => {
  queryClient.invalidateQueries({
    predicate: (query) => query.state.isInvalidated, // missed events never set this
  });
});

Correct (invalidate what the socket owns):

function useWebSocketWithReconnect() {
  const queryClient = useQueryClient();
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const socket = connectWebSocket();
    socket.on('connect', () => {
      setIsConnected(true);
      // on-screen queries refetch now; the rest refetch when they next mount
      queryClient.invalidateQueries({ queryKey: ['automations'] });
      // or, if the socket drives the whole cache: queryClient.invalidateQueries()
    });
    socket.on('disconnect', () => setIsConnected(false));
    return () => socket.disconnect();
  }, [queryClient]);

  return isConnected;
}

Fallback to polling while disconnected:

const { data } = useQuery({
  queryKey: ['automations', 'detail', id],
  queryFn: () => fetchAutomation(id),
  staleTime: isConnected ? Infinity : 0,
  refetchInterval: isConnected ? false : 5000,
});
  • With staleTime: Infinity, the built-in refetchOnReconnect never fires for this data, because it only refetches stale queries. That is why the socket's own connect event has to trigger the invalidation.

Reference: Query Invalidation · Network Mode · v4 Query Invalidation

7. TypeScript

Impact: MEDIUM

7.1 Type the queryFn, Let TypeScript Infer the Rest

Impact: MEDIUM (cleaner code, inference keeps working for select, data and cache reads) · Versions: v4, v5

Give the queryFn a well-defined return type and let the hook infer data. Explicit generics turn off inference for the remaining type parameters, and most fetch libraries return any, so the typed function is what carries the type.

Incorrect (explicit generics, untyped fetcher):

const { data } = useQuery<Todo[], Error>({
  queryKey: ['todos'],
  queryFn: () => axios.get('/api/todos').then((res) => res.data), // any
});

Correct (typed function, inferred hook):

const fetchTodos = (): Promise<Todo[]> =>
  axios.get('/api/todos').then((res) => res.data);

const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
// data: Todo[] | undefined

const { data: count } = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  select: (todos) => todos.length,
});
// count: number | undefined

Correct (v5): share options with queryOptions / mutationOptions:

import { queryOptions, mutationOptions } from '@tanstack/react-query';

const todoOptions = (id: number) =>
  queryOptions({
    queryKey: ['todos', 'detail', id],
    queryFn: () => fetchTodo(id),
  });

useQuery(todoOptions(5));
const cached = queryClient.getQueryData(todoOptions(5).queryKey);
// cached: Todo | undefined (the key is tagged with the queryFn's type)

const addTodoOptions = () =>
  mutationOptions({ mutationKey: ['addTodo'], mutationFn: addTodo });

useMutation({
  ...addTodoOptions(),
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
});

Correct (v4): no options helpers, so pass a generic when reading the cache:

const todoKeys = {
  detail: (id: number) => ['todos', 'detail', id] as const,
};

useQuery({ queryKey: todoKeys.detail(5), queryFn: () => fetchTodo(5) });
const cached = queryClient.getQueryData<Todo>(todoKeys.detail(5));
  • Inference from queryOptions does not reach getQueriesData, which returns heterogeneous tuples. Pass the generic there.
  • mutationOptions was added to React Query in 5.82. queryOptions has been available since 5.0.
  • To narrow errors, use type guards such as axios.isAxiosError(error) rather than a TError generic. See typescript-register-global-types to change the error type globally.

Reference: TypeScript · v4 TypeScript

7.2 Validate API Responses at Runtime with Zod

Impact: HIGH (catches API contract violations; the parse error becomes the query error) · Versions: v4, v5

Parse the response inside the queryFn instead of asserting a type. The schema is then the single source of truth for the queryFn's return type, so data stays inferred. A failed parse throws, and the query goes to its error state like any other rejected queryFn.

Incorrect (type assertion, unchecked at runtime):

async function fetchTodos() {
  const response = await fetch('/api/todos');
  return (await response.json()) as Todo[]; // trusts the server blindly
}

Correct (schema-validated):

import { z } from 'zod';

const todoSchema = z.object({
  id: z.number(),
  title: z.string(),
  done: z.boolean(),
});
const todosSchema = z.array(todoSchema);
type Todo = z.infer<typeof todoSchema>;

async function fetchTodos(): Promise<Todo[]> {
  const response = await fetch('/api/todos');
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return todosSchema.parse(await response.json()); // throws on mismatch
}

const { data, error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
// data: Todo[] | undefined
  • The TanStack docs ask only for a queryFn with a well-defined return type and do not prescribe a validation library. Any parser that throws on a mismatch works the same way.
  • Validation errors are retried like network errors (3 times by default). If a contract mismatch should fail fast, set retry for that query.

Reference: TypeScript · v4 TypeScript

7.3 Register Global Error, Meta and Key Types

Impact: MEDIUM (app-wide typing without generics at every call site) · Versions: v5 · Since: 5.0

Augment the Register interface once instead of passing generics at every call site. Inference keeps working, and error, meta, queryKey and mutationKey get your types across the whole library surface.

Incorrect (generics and casts at each call site):

const { error } = useQuery<Todo[], ApiError>({ queryKey: ['todos'], queryFn: fetchTodos });
// passing TError turns off inference for the other type parameters

useQuery({ queryKey: ['todos'], queryFn: fetchTodos, meta: { toast: 'oops' } });
// meta is Record<string, unknown>; a typo like `toats` is accepted

Correct (one augmentation, e.g. in src/react-query.d.ts):

import '@tanstack/react-query';

type AppMeta = { errorMessage?: string }; // a type alias, so unknown keys like `toats` are rejected

type AppQueryKey = ['todos' | 'users' | 'settings', ...ReadonlyArray<unknown>];

declare module '@tanstack/react-query' {
  interface Register {
    defaultError: ApiError;   // or `unknown` to force narrowing everywhere
    queryMeta: AppMeta;
    mutationMeta: AppMeta;
    queryKey: AppQueryKey;    // since 5.64
    mutationKey: AppQueryKey; // since 5.64
  }
}

const { error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
//      ^? ApiError | null, and data is still inferred

useQuery({ queryKey: ['todoz'], queryFn: fetchTodos }); // type error: not a registered key root
  • The meta types must extend Record<string, unknown>. Key types must extend an array type.
  • Registered meta pairs well with global callbacks such as new QueryCache({ onError: (error, query) => toast(query.meta?.errorMessage) }).
  • v4 has no Register; its errors are unknown. v4 can still type meta by augmenting the QueryMeta / MutationMeta interfaces. Upgrade first (see migration-error-type-default).

Reference: TypeScript

8. Testing

Impact: MEDIUM

8.1 Fresh QueryClient Per Test

Impact: CRITICAL (test isolation, no cache bleed between tests, no retry timeouts) · Versions: v4, v5

Build a new QueryClient and QueryClientProvider inside the wrapper factory so each test starts with an empty cache. Turn off retries in the defaults so error-state tests don't time out on the three default retries with exponential backoff.

Incorrect (one client shared across tests):

const queryClient = new QueryClient(); // cache leaks from test 1 into test 2

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);

Correct (v5):

function createWrapper() {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        gcTime: Infinity, // Jest: avoids "Jest did not exit one second after the test run"
      },
    },
  });
  return ({ children }: { children: React.ReactNode }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
}

it('loads todos', async () => {
  const { result } = renderHook(() => useTodos(), { wrapper: createWrapper() });
  await waitFor(() => expect(result.current.isSuccess).toBe(true));
});

Correct (v4):

function createWrapper() {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
    logger: { log: console.log, warn: console.warn, error: () => {} }, // v4 only
  });
  return ({ children }: { children: React.ReactNode }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
}
  • retry: false in the defaults is only a fallback. A query that sets its own retry still retries in tests.
  • Mutations already default to retry: 0.
  • Setting gcTime/cacheTime to Infinity matches the server default. It is only needed if you set a custom value somewhere.
  • v5 removed the logger option, and passing it is a type error. v5 logs only in development.
  • A single shared wrapper is acceptable only if the client is cleared before every test and tests don't run in parallel.

Reference: Testing · v4 Testing

8.2 Mock the Network, Not useQuery

Impact: HIGH (tests exercise the real hook, cache and error paths) · Versions: v4, v5

Test your custom hooks against a mocked network layer (MSW, or nock as the TanStack docs use) instead of mocking useQuery. The query function, the cache and the status transitions then run for real. The React Query code is the same in v4 and v5; the split below is between MSW majors.

Incorrect (mocking the library):

vi.mock('@tanstack/react-query', () => ({
  useQuery: () => ({ data: [{ id: 1 }], isSuccess: true }),
}));

Correct (MSW 2.x):

// mocks/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('/api/todos', () =>
    HttpResponse.json([{ id: 1, title: 'Todo 1', done: false }]),
  ),
];

// setupTests.ts
import { setupServer } from 'msw/node';
export const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

// todos.test.tsx
it('handles error state', async () => {
  server.use(
    http.get('/api/todos', () =>
      HttpResponse.json({ message: 'boom' }, { status: 500 }),
    ),
  );
  const { result } = renderHook(() => useTodos(), { wrapper: createWrapper() });
  await waitFor(() => expect(result.current.isError).toBe(true));
});

Correct (MSW 1.x, legacy):

import { rest } from 'msw';

rest.get('/api/todos', (req, res, ctx) => res(ctx.json([{ id: 1 }])));
rest.get('/api/todos', (req, res, ctx) => res(ctx.status(500)));
  • An error test only reaches isError quickly if retries are off (see testing-fresh-client), and only if the queryFn rejects on non-2xx responses (see troubleshoot-fetch-not-reject).
  • Use waitFor until the status says the request settled before asserting on data.

Reference: Testing · v4 Testing · MSW http

9. Tooling

Impact: MEDIUM

9.1 Enable the TanStack Query ESLint Plugin

Impact: HIGH (catches missing key deps, lost render optimizations and unstable clients at lint time) · Versions: v4, v5

Install @tanstack/eslint-plugin-query and enable its recommended config. Several mistakes other rules in this guide warn about become lint errors: missing query-key dependencies, rest destructuring, unstable deps, query functions with no return value, and a QueryClient created on every render.

Incorrect (no plugin; these pass review unnoticed):

function App() {
  const queryClient = new QueryClient(); // new cache on every render
  const { data, ...rest } = useQuery({ queryKey: ['todo'], queryFn: () => api.getTodo(todoId) });
}

Correct (v5, flat config; flat support shipped with 5.50):

// npm i -D @tanstack/eslint-plugin-query
import pluginQuery from '@tanstack/eslint-plugin-query';

export default [
  ...pluginQuery.configs['flat/recommended'], // or 'flat/recommended-strict'
];

Correct (v5, legacy .eslintrc):

{ "extends": ["plugin:@tanstack/query/recommended"] }

Correct (v4, .eslintrc):

{ "extends": ["plugin:@tanstack/eslint-plugin-query/recommended"] }

Rules in the current (v5) plugin. The release that added each rule is in parentheses where the changelog records it:

RuleConfigCatches
exhaustive-depsrecommendedqueryFn variables missing from queryKey (query-keys-as-dependencies)
stable-query-clientrecommended, fixablenew QueryClient() inside a component or hook
no-rest-destructuring (5.6)recommended (warn){ data, ...rest } = useQuery() (query-tracked-properties)
no-unstable-deps (5.52)recommendedthe query or mutation result object in hook dependency arrays
infinite-query-property-order (5.57)recommended, fixableproperty order that breaks infinite-query type inference
no-void-query-fn (5.71)recommendeda queryFn with no return value; needs typed linting, and reports nothing under Oxlint
mutation-property-order (5.78)recommended, fixableonMutate order that breaks mutation inference
prefer-query-options (react-query 5.96)recommended-strictkey and fn defined without queryOptions, or hand-typed keys in QueryClient calls (query-options-helper)
  • exhaustive-deps accepts allowlist.variables and allowlist.types for stable clients and config objects.
  • Turn off no-rest-destructuring only if you set notifyOnChangeProps manually.
  • v4: the plugin ships four rules, all in recommended: exhaustive-deps, stable-query-client, prefer-query-object-syntax and no-deprecated-options. The last two flag code v5 removes (positional signatures, and options such as onSuccess on useQuery), so turning them on before a v5 upgrade shrinks the migration. v5 dropped both: delete prefer-query-object-syntax and no-deprecated-options from any explicit rule config when upgrading, or ESLint fails with "Definition for rule … was not found".

Reference: ESLint Plugin Query · v4 ESLint Plugin Query

10. Common Pitfalls

Impact: MEDIUM

10.1 Copying Query Data to State

Impact: HIGH (keeps the cache as the single source of truth) · Versions: v4, v5

Read server data from the query, not from a useState copy. The cache updates after background refetches, invalidations and setQueryData, and a local copy misses all of them. Derive values with select, and reach the same data elsewhere by calling the same query hook.

Incorrect (duplicated state synced by an effect):

const { data } = useQuery({ queryKey: ['user'], queryFn: fetchUser });
const [user, setUser] = useState(data);

useEffect(() => {
  if (data) setUser(data);
}, [data]);

Correct (read the query; derive with select):

const { data: user } = useQuery({ queryKey: ['user'], queryFn: fetchUser });

const { data: userName } = useQuery({
  queryKey: ['user'],
  queryFn: fetchUser,
  select: (user) => user.name,
});

Incorrect (getQueryData used as a global store in render):

function Header() {
  const user = queryClient.getQueryData(['user']); // non-reactive: Header never updates
  return <span>{user?.name}</span>;
}

Correct (call the query hook again; it is deduplicated and served from cache):

const useUser = () => useQuery({ queryKey: ['user'], queryFn: fetchUser, staleTime: 5 * 60 * 1000 });

function Header() {
  const { data: user } = useUser();
  return <span>{user?.name}</span>;
}
  • queryClient.getQueryData is an imperative, non-reactive read. Use it only in callbacks that need the latest value, such as optimistic updates.
  • Several components using the same key share one cache entry. A second instance gets the cached data immediately, and set a staleTime if it should not trigger a background refetch as well.

Reference: Does TanStack Query replace client state? · QueryClient.getQueryData · v4 Does this replace client state?

10.2 Fetch Not Rejecting on Errors

Impact: HIGH (HTTP errors otherwise land in the cache as successful data) · Versions: v4, v5

A query fails only when its queryFn throws or returns a rejected promise. fetch resolves on 4xx/5xx responses, so check response.ok and throw. Otherwise the error body is cached as data, error stays null, and retries never run.

Incorrect (404 treated as success):

useQuery({
  queryKey: ['user', id],
  queryFn: () => fetch(`/api/users/${id}`).then((res) => res.json()),
});

Correct (throw on non-OK responses):

useQuery({
  queryKey: ['user', id],
  queryFn: async () => {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) {
      throw new Error(`Request failed: ${res.status}`);
    }
    return res.json();
  },
});

Correct (a client that rejects by itself, e.g. axios or graphql-request):

useQuery({
  queryKey: ['user', id],
  queryFn: () => axios.get(`/api/users/${id}`).then((res) => res.data),
});
  • Return a value from the queryFn. Resolving undefined is treated as a failure, so resolve null to cache "nothing". The ESLint rule no-void-query-fn catches missing returns (requires typed linting).
  • Errors are retried 3 times with exponential backoff before error is set (v5 doesn't retry on the server by default; v4 does). The in-progress error is exposed as failureReason until the last attempt (v4.13+ and v5).
  • v5 types error as Error by default (v4: unknown). If you throw something other than an Error, set the generic or register a global error type.

Reference: Query Functions · Query Retries · v4 Query Functions

11. Migration v4 → v5

Impact: HIGH

11.1 Single Object Signature Required

Impact: HIGH (breaking change, every positional-argument call must be rewritten) · Versions: v4, v5

In v5, hooks, QueryClient methods and queryCache.find/findAll accept only a single options object. The positional overloads are gone. They are type errors, and React Query also throws a development-mode error for malformed useQuery calls. getQueryData and getQueryState now take just the queryKey.

v4 (before):

useQuery(['todos'], fetchTodos, { staleTime: 5000 });
useMutation(postTodo, { onSuccess });
useIsFetching(['todos']);

queryClient.invalidateQueries(['todos'], { exact: true });
queryClient.getQueryData(['todo', id], { exact: true });
queryClient.fetchQuery(['todo', id], () => fetchTodo(id));

v5 (after):

useQuery({ queryKey: ['todos'], queryFn: fetchTodos, staleTime: 5000 });
useMutation({ mutationFn: postTodo, onSuccess });
useIsFetching({ queryKey: ['todos'] });

queryClient.invalidateQueries({ queryKey: ['todos'], exact: true });
queryClient.getQueryData(['todo', id]); // key only, no filters
// 5.102+: fetchQuery is deprecated in favour of query()
queryClient.query({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) });
// before 5.102: queryClient.fetchQuery({ queryKey: ['todo', id], queryFn: … })

Codemod (remove-overloads):

npx jscodeshift@latest ./src --extensions=ts,tsx --parser=tsx \
  --transform=./node_modules/@tanstack/react-query/build/codemods/v5/remove-overloads/remove-overloads.cjs
  • --parser=tsx is required for TypeScript files, or the transform is not applied. For .js/.jsx, use --extensions=js,jsx and drop the parser flag.
  • The codemod skips calls whose first argument is already an object with queryKey/mutationKey. Calls it cannot infer are logged, sometimes with only the file name ("An unknown error occurred while processing"), so fix those by hand. It converts useQuery, useMutation, useIsFetching, useIsMutating and the QueryClient filter and fetch methods, but only on clients created in the same file with new QueryClient() or useQueryClient(): calls on an imported client are skipped without a warning. Two-argument fetchQuery(key, fn) / prefetchQuery(key, fn) fail with that unknown error. useInfiniteQuery, useQueries, getQueryData(key, filters) and setQueriesData are not handled. Run prettier/eslint afterwards.
  • The codemod does not move fetchQuery/prefetchQuery/ensureQueryData to query(); see query-imperative-query-method.

Reference: Migrating to v5

11.2 Status "loading" Renamed to "pending

Impact: HIGH (breaking change, and isLoading silently changes meaning) · Versions: v4, v5

In v5, status: 'loading' became 'pending' and isLoading became isPending, for queries and mutations alike. A new isLoading on queries means isPending && isFetching, which is what v4's isInitialLoading meant. isInitialLoading is deprecated.

v4 (before):

const { status, isLoading, isInitialLoading } = useQuery({ queryKey, queryFn });
if (status === 'loading') return <Spinner />;
if (isInitialLoading) return <Spinner />;

const mutation = useMutation({ mutationFn });
<button disabled={mutation.isLoading} />;

v5 (after):

const { status, isPending, isLoading } = useQuery({ queryKey, queryFn });
if (status === 'pending') return <Spinner />;
if (isLoading) return <Spinner />; // pending AND fetching (was isInitialLoading)

const mutation = useMutation({ mutationFn });
<button disabled={mutation.isPending} />;

Codemod (is-loading, since 5.9):

npx jscodeshift@latest ./src --extensions=ts,tsx --parser=tsx \
  --transform=./node_modules/@tanstack/react-query/build/codemods/v5/is-loading/is-loading.cjs
  • The rename keeps v4 behaviour: v4 isLoading is v5 isPending. An isLoading left unrenamed now means pending and fetching, which is false for a disabled query, so it silently changes what renders.
  • The codemod only targets useQuery and useMutation results, skips isInitialLoading, and once it finds a destructured isLoading it renames every isLoading identifier in that scope, unrelated ones included. Review its diff.
  • v4.40+ mutations already expose isPending.
  • The codemod renames the isLoading flag only. Replace status === 'loading' with status === 'pending' by hand, in query and mutation checks alike.

Reference: Migrating to v5

11.3 cacheTime Renamed to gcTime

Impact: HIGH (breaking change; the old option is a type error and is ignored at runtime) · Versions: v4, v5

v5 renamed cacheTime to gcTime. The option does nothing while a query is in use. It is the time an unused query is kept before it is garbage collected, which "cacheTime" made sound like something else. The default is still 5 minutes.

v4 (before):

const queryClient = new QueryClient({
  defaultOptions: { queries: { cacheTime: 10 * 60 * 1000 } },
});

useQuery({ queryKey: ['todos'], queryFn: fetchTodos, cacheTime: 10 * 60 * 1000 });

v5 (after):

const queryClient = new QueryClient({
  defaultOptions: { queries: { gcTime: 10 * 60 * 1000 } },
});

useQuery({ queryKey: ['todos'], queryFn: fetchTodos, gcTime: 10 * 60 * 1000 });

Codemod (rename-properties, also renames useErrorBoundary → throwOnError):

npx jscodeshift@latest ./src --extensions=ts,tsx --parser=tsx \
  --transform=./node_modules/@tanstack/react-query/build/codemods/v5/rename-properties/rename-properties.cjs
  • When persisting the cache, keep gcTime at or above the persister's maxAge (24h by default), or garbage collection discards the stored cache earlier than expected.

Reference: Migrating to v5

11.4 useErrorBoundary Renamed to throwOnError

Impact: MEDIUM (breaking change; errors stop reaching the error boundary until renamed) · Versions: v4, v5

v5 renamed the useErrorBoundary option to throwOnError on queries and mutations. The new name avoids the hook-style use prefix and describes what the option does: it re-throws the error so the nearest error boundary catches it. It still accepts a boolean or a function.

v4 (before):

useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  // only throw when there is no cached data to show
  useErrorBoundary: (error, query) => typeof query.state.data === 'undefined',
});

useMutation({ mutationFn: postTodo, useErrorBoundary: true });

v5 (after):

useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  throwOnError: (error, query) => typeof query.state.data === 'undefined',
});

useMutation({ mutationFn: postTodo, throwOnError: true });

Codemod (rename-properties, also renames cacheTime → gcTime):

npx jscodeshift@latest ./src --extensions=ts,tsx --parser=tsx \
  --transform=./node_modules/@tanstack/react-query/build/codemods/v5/rename-properties/rename-properties.cjs

Reference: Migrating to v5

11.5 keepPreviousData Replaced by placeholderData Function

Impact: HIGH (breaking change, common in pagination/filtering UIs) · Versions: v4, v5

v5 removed the keepPreviousData option and the isPreviousData flag, because they did mostly the same thing as placeholderData and isPlaceholderData. placeholderData now receives the previous query's data, so pass an identity function or the exported keepPreviousData helper.

v4 (before):

const { data, isPreviousData } = useQuery({
  queryKey: ['projects', page],
  queryFn: () => fetchProjects(page),
  keepPreviousData: true,
});

v5 (after):

import { keepPreviousData, useQuery } from '@tanstack/react-query';

const { data, isPlaceholderData } = useQuery({
  queryKey: ['projects', page],
  queryFn: () => fetchProjects(page),
  placeholderData: keepPreviousData, // same as (previousData) => previousData
});

Codemod (run the object-syntax migration first; it transforms only calls whose first argument is an object literal):

npx jscodeshift@latest ./src --extensions=ts,tsx --parser=tsx \
  --transform=./node_modules/@tanstack/react-query/build/codemods/v5/keep-previous-data/keep-previous-data.cjs

The codemod moves the option only: rename isPreviousData to isPlaceholderData by hand.

Behaviour differences to check after migrating:

  • Both report success while showing the previous data. The difference: v4 keepPreviousData kept data only when the previous query was in success; v5 placeholderData: keepPreviousData keeps the last defined data even if that query errored.
  • The codemod converts only the literal keepPreviousData: true (other values get a warning) and adds the keepPreviousData import. It covers useQuery, useInfiniteQuery, useQueries, setQueryDefaults and new QueryClient({ defaultOptions }).
  • dataUpdatedAt stays 0 while placeholder data is shown. keepPreviousData exposed the previous data's timestamp.
  • Suspense hooks do not accept placeholderData; use startTransition there.

Reference: Migrating to v5, Paginated Queries, v4 Paginated Queries

11.6 Query Callbacks Removed from useQuery

Impact: HIGH (breaking change, callbacks are type errors and never fire in JS) · Versions: v4, v5

v5 removed onSuccess, onError and onSettled from useQuery and QueryObserver. They remain on mutations. Global reactions such as error toasts move to the QueryCache callbacks. Per-component effects move to the component, driven by the query result.

v4 (before):

useQuery({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId),
  onSuccess: (data) => analytics.track('user_loaded', { id: data.id }),
  onError: (error) => toast.error((error as Error).message), // v4 types error as unknown
});

v5 (after): global error handling on the cache:

import { QueryCache, QueryClient } from '@tanstack/react-query';

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => toast.error(error.message),
  }),
});

v5 (after): component-level side effects from the result:

const { data } = useQuery({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId),
});

useEffect(() => {
  if (data) analytics.track('user_loaded', { id: data.id });
}, [data]);
  • To change data, use select, not a callback that writes into state (see troubleshoot-copy-to-state).
  • useMutation keeps onSuccess/onError/onSettled; see mutation-callback-separation.
  • There is no codemod for this change. The motivation is laid out in the RFC linked from the migration guide.

Reference: Migrating to v5 · QueryCache

11.7 New Dedicated Suspense Hooks

Impact: HIGH (the suspense option is a type error in v5; the dedicated hooks are the supported path) · Versions: v4, v5

v5 removed the experimental suspense: boolean flag from the types. Suspense now uses dedicated hooks, and data is typed as always defined because loading and error states are handled by <Suspense> and error boundaries. Plain JS that still passes suspense: true keeps suspending through an untyped code path, so don't rely on it. v4.39+ already exports useSuspenseQuery and useSuspenseQueries (useSuspenseInfiniteQuery from 4.41), so you can switch before upgrading.

v4 (before):

const { data } = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  suspense: true,
});
// data: TData | undefined

v5 (after):

import { useSuspenseQuery } from '@tanstack/react-query';

const { data } = useSuspenseQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
});
// data: TData

Available hooks: useSuspenseQuery, useSuspenseInfiniteQuery, useSuspenseQueries.

What changes when you switch:

  • enabled, placeholderData and throwOnError are not accepted, and queryFn cannot be skipToken. You cannot conditionally disable a suspense query.
  • status is only success or error, and isPlaceholderData is not on the result.
  • Instead of placeholderData, wrap updates that change the query key in startTransition so the fallback does not replace the UI. useSuspenseInfiniteQuery also lost placeholderData from its types in 5.102.
  • Errors are thrown to the error boundary only when there is no cached data; a failed background refetch keeps rendering the cached data. Throw error yourself if every error must reach the boundary.
  • Several useSuspenseQuery calls in one component fetch one after another; use useSuspenseQueries for parallel fetching (see suspense-parallel-queries).
  • The experimental_prefetchInRender option and the promise result property for React.use() (added in 5.59) were removed in 5.102. Use these hooks instead.

Reference: Suspense, Migrating to v5, v4 Suspense

11.8 Hydrate Component Renamed to HydrationBoundary

Impact: MEDIUM (breaking change for SSR/Next.js apps) · Versions: v4, v5

In v5, <Hydrate> was renamed to <HydrationBoundary> and the useHydrate hook was removed. The hydration APIs were changed to better support concurrent features and transitions.

v4 (before):

import { Hydrate, QueryClientProvider } from '@tanstack/react-query';

<QueryClientProvider client={queryClient}>
  <Hydrate state={dehydratedState}>{children}</Hydrate>
</QueryClientProvider>;

dehydrate(queryClient, { dehydrateMutations: false });

v5 (after):

import { HydrationBoundary, QueryClientProvider } from '@tanstack/react-query';

<QueryClientProvider client={queryClient}>
  <HydrationBoundary state={dehydratedState}>{children}</HydrationBoundary>
</QueryClientProvider>;

dehydrate(queryClient, { shouldDehydrateMutation: () => false });

Codemod:

npx jscodeshift@latest ./src --extensions=ts,tsx --parser=tsx \
  --transform=./node_modules/@tanstack/react-query/build/codemods/v5/rename-hydrate/rename-hydrate.cjs

The codemod renames the Hydrate import and JSX only, and aborts the file on a self-closing <Hydrate state={s} />. Migrate useHydrate and the dehydrate options by hand.

Other hydration changes in v5:

  • HydrationBoundary hydrates only queries. To hydrate mutations, call the low-level hydrate() or use the persistQueryClient plugin.
  • Timing: new queries are still hydrated during render, so SSR works as before. Queries already in the cache are hydrated in an effect, and only when the incoming data is newer. With Server Components passing fresh data on navigation, you may briefly see the old data. No action is needed.
  • dehydrate's boolean dehydrateQueries / dehydrateMutations options were removed. Use the shouldDehydrateQuery / shouldDehydrateMutation predicates instead (() => false restores the old opt-out).
  • Since 5.84 the state prop is strictly typed as DehydratedState | null | undefined.

Reference: Migrating to v5, HydrationBoundary, v4 SSR

11.9 initialPageParam Required for Infinite Queries

Impact: HIGH (breaking change, every useInfiniteQuery needs an update) · Versions: v4, v5

In v5, every infinite query must declare initialPageParam; it is used as the pageParam of the first page. In v4 the first pageParam was undefined, which you defaulted in the queryFn signature. That stored undefined in the cache, and undefined is not serializable.

v4 (before):

useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam = 0 }) => fetchProjects(pageParam),
  getNextPageParam: (lastPage) => lastPage.nextCursor,
});

v5 (after):

useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam }) => fetchProjects(pageParam),
  initialPageParam: 0,
  getNextPageParam: (lastPage) => lastPage.nextCursor,
});

Manual page params were removed in v5. You can no longer override the next param by passing it to fetchNextPage / fetchPreviousPage, and getNextPageParam is now required. This feature never worked with refetches.

// v4 (before): override the param by hand
fetchNextPage({ pageParam: cursorFromSomewhere });

// v5 (after): getNextPageParam is the only source of the next param
useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam }) => fetchProjects(pageParam),
  initialPageParam: 0,
  getNextPageParam: (lastPage, allPages, lastPageParam) =>
    lastPage.items.length === 0 ? undefined : lastPageParam + 1,
});
fetchNextPage();

Ending the list: return undefined or null. v4's hasNextPage also accepted false; v5 does not. A v4 getter that returns false now leaves hasNextPage true, and fetchNextPage calls the queryFn with pageParam: false.

Reference: Migrating to v5, Infinite Queries, v4 Infinite Queries

11.10 refetchPage Replaced by maxPages

Impact: MEDIUM (breaking change for infinite queries) · Versions: v4, v5

v5 removed refetchPage, which in v4 chose which pages of an infinite query to refetch. It was never a useInfiniteQuery option: it lived on the result's refetch() and on the refetchQueries / invalidateQueries / resetQueries filters, where it did nothing for normal queries. Refetching only some pages could leave the UI inconsistent. Use maxPages instead: it limits how many pages are stored, and therefore how many are refetched.

v4 (before):

const { refetch } = useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam = 0 }) => fetchProjectsPage(pageParam),
  getNextPageParam: (lastPage) => lastPage.nextCursor,
});
refetch({ refetchPage: (_page, index) => index < 2 });

queryClient.refetchQueries({
  queryKey: ['projects'],
  refetchPage: (_page, index) => index === 0,
});

v5 (after):

useInfiniteQuery({
  queryKey: ['projects'],
  queryFn: ({ pageParam }) => fetchProjectsPage(pageParam),
  initialPageParam: 0,
  getNextPageParam: (lastPage) => lastPage.nextCursor,
  getPreviousPageParam: (firstPage) => firstPage.prevCursor,
  maxPages: 3,
});
  • maxPages requires a bi-directional list: define both getNextPageParam and getPreviousPageParam. Pages dropped from one end can then be fetched again when the user scrolls back.
  • On refetch, only the stored pages (at most maxPages) are refetched, one after another.

Reference: Migrating to v5, Infinite Queries, v4 Infinite Queries

11.11 Error Is the Default Error Type in v5

Impact: MEDIUM (type-level breaking change; narrowing code and non-Error throws need review) · Versions: v4, v5

In v4, error was typed unknown. In v5 it defaults to Error, because that is almost always what gets thrown. Delete casts that only existed to get from unknown to Error. If you throw something that is not an Error, declare that explicitly, either per call or globally via Register.

v4 (before):

const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups });
//      ^? unknown
const message = error instanceof Error ? error.message : 'Unknown error';

useQuery<number, string>({ queryKey: ['n'], queryFn }); // generics needed in both

v5 (after):

const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups });
//      ^? Error | null
const message = error?.message;

// throwing a non-Error still needs explicit generics (this disables inference for the rest)
useQuery<number, string>({
  queryKey: ['n'],
  queryFn: async () => {
    if (Math.random() > 0.5) throw 'some error';
    return 42;
  },
});

v5: keep the v4 strictness everywhere with Register:

declare module '@tanstack/react-query' {
  interface Register {
    defaultError: unknown; // call sites must narrow explicitly
  }
}
  • For subclasses such as AxiosError, narrow with a type guard (axios.isAxiosError(error)) rather than a generic.
  • See typescript-register-global-types for registering a specific error class.

Reference: Migrating to v5 · TypeScript

11.12 remove() Method Removed from useQuery

Impact: MEDIUM (breaking change, refactor required where used) · Versions: v4, v5

In v5, the remove() method on the useQuery result was removed. Use queryClient.removeQueries() instead.

Why: removing a query that a mounted component still observes only causes a hard loading state on its next render. Removal is meant for imperative cleanup such as logout, which queryClient.removeQueries covers. Both call the same queryCache.remove, so behaviour is unchanged.

v4 (before):

const query = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
});

const handleReset = () => {
  query.remove();
};

v5 (after):

const queryClient = useQueryClient();
const query = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
});

const handleReset = () => {
  queryClient.removeQueries({ queryKey: ['todos'], exact: true });
};

remove() dropped only this exact query. Without exact: true, removeQueries({ queryKey: ['todos'] }) also removes ['todos', …].

Reference: Migrating to v5

11.13 refetchInterval Callback Signature Changed

Impact: LOW (breaking change for dynamic polling intervals) · Versions: v4, v5

In v5, the refetchInterval callback receives only the query object — no longer (data, query). Read data from query.state.data.

Why: Aligns with other callback signatures (e.g. refetchOnWindowFocus) and fixes typing issues: v4's data argument was the select-transformed value, while query.state.data is raw. The v5 callback may also return undefined.

v4 (before):

useQuery({
  queryKey: ['job', id],
  queryFn: () => fetchJob(id),
  refetchInterval: (data, query) =>
    data?.status === 'done' ? false : 5000,
});

v5 (after):

useQuery({
  queryKey: ['job', id],
  queryFn: () => fetchJob(id),
  refetchInterval: (query) =>
    query.state.data?.status === 'done' ? false : 5000,
});
  • query.state.data is the raw cached data: select has not run on it.

Reference: Migrating to v5

11.14 Custom context and contextSharing Replaced by a queryClient Argument

Impact: LOW (breaking change for micro-frontends and apps with several QueryClients) · Versions: v4, v5

v5 removed the context option from hooks and the contextSharing prop from QueryClientProvider. For isolation, pass a specific QueryClient as the hook's second argument. To share a client across bundles or packages, pass the same client instance everywhere.

v4 (before):

const customContext = React.createContext<QueryClient | undefined>(undefined);

<QueryClientProvider client={queryClient} context={customContext}>
  <App />
</QueryClientProvider>;

useQuery({ queryKey: ['todos'], queryFn: fetchTodos, context: customContext });

// contextSharing was already deprecated in v4
<QueryClientProvider client={queryClient} contextSharing={true}>
  <App />
</QueryClientProvider>;

v5 (after):

import { sharedQueryClient } from './query-client';

useQuery({ queryKey: ['todos'], queryFn: fetchTodos }, sharedQueryClient);
useMutation({ mutationFn: addTodo }, sharedQueryClient);

<QueryClientProvider client={sharedQueryClient}>
  <App />
</QueryClientProvider>;

Reference: Migrating to v5

11.15 dehydrate Boolean Options Replaced by Predicates

Impact: LOW (breaking change for SSR and persistence code that filters dehydration) · Versions: v4, v5

v5 removed the dehydrateQueries and dehydrateMutations booleans from dehydrate. Pass the predicate functions shouldDehydrateQuery and shouldDehydrateMutation instead. Use () => false to skip a kind entirely. If you don't pass them, the defaults dehydrate successful queries and paused mutations.

v4 (before):

import { dehydrate } from '@tanstack/react-query';

const state = dehydrate(queryClient, {
  dehydrateQueries: true,
  dehydrateMutations: false,
});

v5 (after):

import { dehydrate, defaultShouldDehydrateQuery } from '@tanstack/react-query';

const state = dehydrate(queryClient, {
  shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query),
  shouldDehydrateMutation: () => false,
});
  • <HydrationBoundary> (formerly <Hydrate>) hydrates only queries in v5. To restore mutations, use the low-level hydrate() or the persistQueryClient plugin (see migration-hydration-boundary).

Reference: Migrating to v5 · dehydrate

11.16 Misc v5 Breaking Changes

Impact: MEDIUM (smaller breaking changes that are easy to miss during an upgrade) · Versions: v4, v5

Check each of these when moving from v4 to v5. Most show up as type errors. The last group changes runtime behaviour without any compile-time signal.

Platform floors: React 18.0+ (v5 uses useSyncExternalStore; the peer range is now ^18 || ^19). TypeScript 4.7+ at 5.0, with current docs supporting 5.7+ (see upgrade-toolchain-floors). Modern browsers only: Chrome/Edge 91, Firefox 90, Safari/iOS 15, Opera 77.

Removed or renamed APIs (v4 before → v5 after):

// custom logger: removed; logging only happens in development
new QueryClient({ logger: myLogger });          // v4
new QueryClient();                              // v5

// hashQueryKey → hashKey (it hashes mutation keys too)
import { hashQueryKey } from '@tanstack/react-query'; // v4
import { hashKey } from '@tanstack/react-query';      // v5

// isDataEqual → structuralSharing
useQuery({ queryKey, queryFn, isDataEqual: eq });                  // v4
useQuery({ queryKey, queryFn,                                      // v5
  structuralSharing: (old, next) => (eq(old, next) ? old : replaceEqualDeep(old, next)) });

// manual pageParam override removed; getNextPageParam is now required
fetchNextPage({ pageParam: 5 });                // v4
fetchNextPage();                                // v5, page params come only from the getters
  • getNextPageParam / getPreviousPageParam end the list with undefined or null only. A v4 getter that returned false (which v4's hasNextPage accepted) is no longer treated as the end (see migration-initial-page-param).
  • ESLint: delete @tanstack/query/prefer-query-object-syntax from your config, because the rule no longer exists.
  • See also migration-error-type-default (the error type is now Error) and migration-dehydrate-options.

Behaviour changes (no type error):

  • Query defaults merge. getQueryDefaults now merges every matching setQueryDefaults registration instead of returning only the first match. Register from the most generic key to the most specific, and re-add overrides that a generic default now leaks into:
queryClient.setQueryDefaults(['todo'], { retry: false, staleTime: 60_000 });
queryClient.setQueryDefaults(['todo', 'detail'], { retry: true, staleTime: 10_000 });
  • No retries on the server. retry defaults to 0 on the server (it was 3). Set it per query if SSR should retry.
  • Window focus. Only visibilitychange triggers focus refetching; the focus event is ignored.
  • Online status. v5 no longer reads navigator.onLine. It starts online: true and follows online/offline events. Offline-first apps loaded from a service worker can see false "online" positives.
  • Private fields. Internals are now real #private class fields. Code that reached into TS-private members gets undefined.
  • Batching. unstable_batchedUpdates is no longer installed as the batch function, since it is a no-op in React 18. Use notifyManager.setBatchNotifyFunction only if your renderer needs one.

Reference: Migrating to v5 · Installation requirements

12. Upgrading within v5

Impact: HIGH

12.1 Drop Trailing undefined from Partial Key Filters

Impact: HIGH (invalidations that silently stop matching after 5.103) · Versions: v5 · Since: 5.103

Since 5.103, a partial-match filter key that is longer than a cached key, because its extra trailing elements are undefined, no longer matches that shorter key. Before, ['todos', undefined] matched ['todos']. Key factories with optional parameters create these filters easily, and nothing reports it: the invalidation simply stops hitting the query. Build filter keys without trailing undefined, or invalidate by the shared prefix.

Incorrect (relies on pre-5.103 matching):

const todoKeys = {
  all: ['todos'] as const,
  list: (filter?: string) => ['todos', filter] as const,
};

useQuery({ queryKey: todoKeys.all, queryFn: fetchAllTodos });

// filter is undefined → ['todos', undefined]
queryClient.invalidateQueries({ queryKey: todoKeys.list(filter) });
// ≤5.102: invalidated ['todos'] · ≥5.103: no longer matches ['todos']

Correct (no trailing undefined in the filter):

const todoKeys = {
  all: ['todos'] as const,
  list: (filter?: string) =>
    filter === undefined ? (['todos', 'list'] as const) : (['todos', 'list', filter] as const),
};

// invalidate everything under the prefix
queryClient.invalidateQueries({ queryKey: todoKeys.all });
  • Audit every filter-taking call (invalidateQueries, refetchQueries, cancelQueries, removeQueries, resetQueries, setQueriesData, useIsFetching, useMutationState) whose key is built from optional arguments.
  • Prefix matching is otherwise unchanged. ['todos'] still matches ['todos', 'list', 'done'].

Reference: Query Filters · PR #11502

12.2 Replace Experimental APIs Removed in v5 Minors

Impact: MEDIUM (type errors and runtime failures after upgrading to 5.86 / 5.102) · Versions: v5 · Since: 5.102

Several experimental APIs were removed or reshaped inside v5. They show up as type errors, or at runtime as undefined values. Move to the stable equivalents before (or while) upgrading.

5.102: experimental_prefetchInRender and the promise result property are gone:

// before (5.59–5.101)
new QueryClient({ defaultOptions: { queries: { experimental_prefetchInRender: true } } });
const { promise } = useQuery(todoOptions(id));
const todo = React.use(promise); // ≥5.102: promise is undefined

// after: Suspense hooks, plus usePrefetchQuery to start the fetch higher up
function Layout({ id }: { id: number }) {
  usePrefetchQuery(todoOptions(id));
  return <Suspense fallback={<Spinner />}><Todo id={id} /></Suspense>;
}
function Todo({ id }: { id: number }) {
  const { data: todo } = useSuspenseQuery(todoOptions(id)); // data is never undefined
}

5.102: placeholderData removed from useSuspenseInfiniteQuery options:

useSuspenseInfiniteQuery({ ...projectsOptions, placeholderData: keepPreviousData }); // before
useSuspenseInfiniteQuery(projectsOptions);                                         // after

Suspense hooks do not accept enabled, placeholderData or skipToken. To keep the old UI while the key changes, wrap the update that changes the key in startTransition.

5.102: the untyped _experimental_beforeQuery / _experimental_afterQuery keys in defaultOptions.queries are no longer read. Delete them from the QueryClient config. There is no replacement.

5.86: experimental_streamedQuery options renamed and reshaped:

import { experimental_streamedQuery as streamedQuery } from '@tanstack/react-query';

// before (5.69–5.85)
queryFn: streamedQuery({ queryFn: fetchChunks, maxChunks: 3 });

// after: queryFn → streamFn; maxChunks removed in favour of a reducer
queryFn: streamedQuery({
  streamFn: fetchChunks,
  reducer: (acc, chunk) => [...acc, chunk].slice(-3), // (acc: TData, chunk) => TData
  initialValue: [] as Chunk[], // required whenever a custom reducer is passed
});

Reference: Suspense · Prefetching · streamedQuery

12.3 Use onMutateResult and the Mutation Function Context

Impact: MEDIUM (clearer callback naming; mutation code can use context.client instead of a closure) · Versions: v5 · Since: 5.89

Since 5.89, mutationFn and every mutation callback get a trailing context argument: a MutationFunctionContext holding client, mutationKey and meta. The value returned from onMutate (formerly called "context") is now named onMutateResult, and the generic is TOnMutateResult (formerly TContext). Positions did not change, so old code still runs. Rename the third argument so it isn't confused with the new context, and use context.client in options defined outside components (e.g. with mutationOptions).

Incorrect (pre-5.89 naming, closes over a client):

useMutation({
  mutationFn: addTodo,
  onMutate: async (newTodo) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] });
    const previousTodos = queryClient.getQueryData<Todo[]>(['todos']);
    return { previousTodos };
  },
  onError: (err, newTodo, context) => {
    queryClient.setQueryData(['todos'], context?.previousTodos);
  },
});

Correct (5.89+):

const addTodoOptions = () =>
  mutationOptions({
    mutationKey: ['addTodo'],
    mutationFn: addTodo,
    onMutate: async (newTodo, context) => {
      await context.client.cancelQueries({ queryKey: ['todos'] });
      const previousTodos = context.client.getQueryData<Todo[]>(['todos']);
      return { previousTodos };
    },
    onError: (err, newTodo, onMutateResult, context) => {
      context.client.setQueryData(['todos'], onMutateResult?.previousTodos);
    },
    onSettled: (data, error, newTodo, onMutateResult, context) =>
      context.client.invalidateQueries({ queryKey: ['todos'] }),
  });

useMutation(addTodoOptions());
  • Signatures: mutationFn(variables, context), onMutate(variables, context), onSuccess(data, variables, onMutateResult, context), onError(error, variables, onMutateResult | undefined, context), onSettled(data, error, variables, onMutateResult | undefined, context).
  • Since 5.90.2, onMutateResult is always defined in the onSuccess passed to useMutation or mutationOptions. The per-call mutate(vars, { onSuccess }) still types it as possibly undefined.
  • mutationOptions needs 5.82+.

Reference: useMutation · MutationFunctionContext

12.4 Move Off APIs Deprecated or Narrowed in v5 Minors

Impact: MEDIUM (deprecated APIs are removed in the next major; narrowed filter types already fail to compile) · Versions: v5 · Since: 5.91

These APIs still work in current v5 but are marked deprecated and are slated for removal in the next major. The filter fields at the end were removed from the types in 5.105, so they already fail to compile. For fetchQuery/prefetchQuery/ensureQueryData (deprecated in 5.102), see query-imperative-query-method.

isServer → environmentManager.isServer() (5.91):

import { isServer } from '@tanstack/react-query';             // before
if (isServer) return makeQueryClient();

import { environmentManager } from '@tanstack/react-query';   // after
if (environmentManager.isServer()) return makeQueryClient();

createSyncStoragePersister → createAsyncStoragePersister (deprecated in 5.81.4):

import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'; // before
const persister = createSyncStoragePersister({ storage: window.localStorage });

import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'; // after
const persister = createAsyncStoragePersister({ storage: window.localStorage }); // sync storages fit the AsyncStorage interface

isCancelledError(err) → err instanceof CancelledError:

import { CancelledError } from '@tanstack/react-query';
if (err instanceof CancelledError) return; // replaces isCancelledError(err)

direction in the infinite QueryFunctionContext (deprecated in 5.35.4): put the direction inside the page param.

type FeedParam = { cursor: number; direction: 'forward' | 'backward' };

useInfiniteQuery({
  queryKey: ['feed'],
  queryFn: ({ pageParam }) => fetchFeed(pageParam.cursor, pageParam.direction), // not ctx.direction
  initialPageParam: { cursor: 0, direction: 'forward' } as FeedParam,
  // annotate the getters: otherwise TPageParam infers `direction: string` and the call fails to compile
  getPreviousPageParam: (first): FeedParam | undefined => first.prev == null ? undefined : { cursor: first.prev, direction: 'backward' },
  getNextPageParam: (last): FeedParam | undefined => last.next == null ? undefined : { cursor: last.next, direction: 'forward' },
});

Filter fields removed from counting APIs (5.105.1 / 5.105.2):

useIsFetching({ queryKey: ['todos'], fetchStatus: 'fetching' }); // before: type error now
useIsFetching({ queryKey: ['todos'] });                          // after: it only ever counts fetching queries
useIsMutating({ mutationKey: ['addTodo'] });                     // same for status on isMutating/useIsMutating

The same fields are gone from queryClient.isFetching and queryClient.isMutating. A repo already on 5.91–5.104 still needs this part: the migrate sweep scopes it since 5.105.

  • isInitialLoading is deprecated in favour of isLoading (see migration-status-pending).

Reference: Advanced SSR · createAsyncStoragePersister · Query Functions

12.5 Keep TypeScript and React Within the Supported Range

Impact: MEDIUM (v5 minors can break type-checking on older TypeScript) · Versions: v5 · Since: 5.100

v5 launched with a TypeScript 4.7 floor, but it now follows DefinitelyTyped's two-year support window: TypeScript 5.7+. Since 5.100.13 the types use TypeScript's built-in NoInfer, which needs TS ≥ 5.4. React must satisfy the peer range ^18 || ^19. Type changes usually ship as patch releases, so the docs recommend pinning an exact version and upgrading on purpose.

Incorrect (old TS, floating range):

{
  "dependencies": { "@tanstack/react-query": "^5.0.0", "react": "^17.0.2" },
  "devDependencies": { "typescript": "~5.3.0" }
}

Correct:

{
  "dependencies": { "@tanstack/react-query": "5.107.1", "react": "^19.0.0" },
  "devDependencies": { "typescript": "^5.7.0" }
}
  • React 18 is the hard floor for all of v5 (useSyncExternalStore). React 19 support landed in 5.39, but the peer range only accepts ^19 from 5.52.1: earlier versions raise peer-dependency errors on install.
  • Type changes are treated as non-breaking and can land in any release. Example: useQuery has returned UseQueryResult<NoInfer<TData>> since 5.75.5 (#8683). In 5.100.13 that switched to the built-in NoInfer (#10593), which broke narrowing of a discriminated-union data (issue #11018). 5.102 reverted it (#11245). If data narrowing broke on 5.100.13–5.101.x, upgrade to 5.102 or later. Re-run the type check on every bump.
  • Browser targets: Chrome/Edge 91, Firefox 90, Safari/iOS 15, Opera 77. Transpile node_modules yourself for older browsers.

Reference: TypeScript · Installation

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.