react-query-best-practices
TanStack Query (React Query) v4 and v5 rules, plus every breaking change up to the latest v5 with its fix. Use when writing, reviewing or debugging code that uses @tanstack/react-query (useQuery, useMutation, queryClient), or when upgrading it.
How do I install this agent skill?
npx skills add https://github.com/arraydude/agent-skills --skill react-query-best-practicesIs this agent skill safe to install?
- Gen Agent Trust Hubpass
The skill provides a comprehensive set of best practices, patterns, and migration guides for React Query v4 and v5. It contains markdown documentation and TypeScript code examples. No security risks were identified.
- Socketpass
No alerts
- Snykpass
Risk: LOW · No issues
- Runlayerpass
29 files scanned · No issues
- ZeroLeakspass
Score: 93/100 · 2 sections analyzed
What does this agent skill do?
React Query Best Practices
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
versionsfrontmatter includes that major. - Skip a rule whose
sinceis 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-querypresent → 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
- React Query is an async state manager, not a fetching library.
- Server state stays in the cache. Keep it out of client-state stores.
- Stale-while-revalidate: cached data shows at once, refetches run in the background.
- Query keys are dependencies: every variable the
queryFnreads goes in the key.
Quick reference
Categories in priority order. Tags: [v5] = v5 only; [v5.102+] = needs that minor. No tag = v4 and v5.
1. Query Keys & Patterns (CRITICAL)
query-keys-as-dependencies- Every changing variable the queryFn reads goes in the keyquery-key-factory- Hierarchical keys from one factory (v5: returnsqueryOptions)query-options-helper[v5] - OnequeryOptionsdefinition for hooks, prefetching and cache readsquery-imperative-query-method[v5.102+] -queryClient.query()replaces fetch/prefetch/ensurequery-dependent-enabled-enabled(orskipTokenin v5) for dependent queriesquery-status-vs-fetch-status-statusis about data,fetchStatusabout the queryFnquery-status-check-order- Pending → error → data, with data-first as the alternativequery-select-transforms- Cache raw data, transform with a stableselectquery-placeholder-vs-initial-initialDatais cached,placeholderDatais not; paginate with previous dataquery-tracked-properties- Destructure only what you read; the result object is not stable
2. Mutations & Updates (CRITICAL)
mutation-invalidation- Invalidate by key prefix and return the promisemutation-optimistic-via-variables- Render pendingvariables: no cache writes, no rollbackmutation-optimistic-updates- Cache-level optimistic update: cancel, snapshot, roll back, return the invalidationmutation-direct-cache-update-setQueryDatafrom the response with anundefined-safe updatermutation-prefer-mutate-mutatewith callbacks;mutateAsynconly for chained or parallel callsmutation-callback-separation- Cache logic in the hook, UI effects at the call sitemutation-state-across-components[v5] -useMutationStateto read mutations elsewheremutation-scope-serial[v5.31+] - Sharedscope.idruns mutations in ordermutation-options-factory[v5.89+] - Share mutation definitions withmutationOptions
3. Caching Strategy (HIGH)
cache-stale-time-staleTimeis the main refetch controlcache-refetch-triggers- Keep refetch triggers on and tunestaleTimeinsteadcache-static-vs-infinity[v5.79+] -Infinitywhen you invalidate,'static'for session-fixed data
4. SSR & Hydration (HIGH)
ssr-query-client-per-request- OneQueryClientper request on the server, never module-levelssr-prefetch-dehydrate-hydrate- Prefetch, dehydrate, hydrate instead ofinitialDatassr-default-stale-time- DefaultstaleTimeabove zero so hydrated data doesn't refetch at once
5. Suspense, Prefetching & Infinite Queries (HIGH)
suspense-parallel-queries[v5] -useSuspenseQueriesinstead of severaluseSuspenseQuerycallsprefetch-flatten-waterfalls- Hoist or prefetch child queries to flatten waterfallsinfinite-query-patterns- GuardedfetchNextPage, aligned pages/pageParams,maxPages
6. WebSocket Integration (HIGH)
websocket-event-invalidation- Socket events carry keys, the client invalidateswebsocket-stale-time-infinity-staleTime: Infinity(not'static') for socket-driven datawebsocket-reconnection- Invalidate what the socket owns on reconnect
7. TypeScript (MEDIUM)
typescript-infer-dont-specify- Type the queryFn, let the hooks infertypescript-zod-validation- Parse responses in the queryFntypescript-register-global-types[v5] -Registerfor error, meta and key types
8. Testing (MEDIUM)
testing-fresh-client- New client per test,retry: falsetesting-msw-mocking- Mock the network with MSW, not the hooks
9. Tooling (MEDIUM)
tooling-eslint-plugin-@tanstack/eslint-plugin-queryrecommended config
10. Common Pitfalls (MEDIUM)
troubleshoot-copy-to-state- Read from the hook; never copy query data into statetroubleshoot-fetch-not-reject- Throw on!res.ok; never resolveundefined
11. Migration v4 → v5 (HIGH)
migration-single-signature- Object-only signatures (codemodremove-overloads)migration-status-pending-loading→pending,isLoading→isPending(codemodis-loading)migration-cache-time-to-gc-time-cacheTime→gcTime(codemodrename-properties)migration-throw-on-error-useErrorBoundary→throwOnError(codemodrename-properties)migration-keep-previous-data-keepPreviousData→placeholderData: keepPreviousData(codemod)migration-query-callbacks-removed- QueryonSuccess/onError/onSettledremovedmigration-suspense-hooks-suspense: true→useSuspenseQueryand siblingsmigration-hydration-boundary-Hydrate→HydrationBoundary(codemodrename-hydrate)migration-initial-page-param-initialPageParamrequired; manualpageParamremovedmigration-refetch-page-to-max-pages-refetchPage→maxPageswith both page gettersmigration-error-type-default-Erroris the default error typemigration-remove-method-query.remove()→queryClient.removeQueries()migration-refetch-interval-callback-refetchIntervalcallback receives onlyquerymigration-context-to-query-client-contextandcontextSharing→queryClientargumentmigration-dehydrate-options-dehydratebooleans →shouldDehydrate*predicatesmigration-misc-breaking-changes- Floors,logger,hashKey,isDataEqual, focus/online, server retry
12. Upgrading within v5 (HIGH)
query-imperative-query-method [v5.102+] also belongs here: it covers the 5.102 deprecations.
upgrade-key-filter-trailing-undefined[v5.103+] - Filters ending inundefinedno longer match shorter keysupgrade-removed-experimental-apis[v5.102+] -promise/experimental_prefetchInRenderand other removed experimentsupgrade-mutation-callback-context[v5.89+] -onMutateResultand the mutation function contextupgrade-deprecated-apis[v5.91+] -isServer, sync persister,isCancelledError,direction, filter fieldsupgrade-toolchain-floors[v5.100+] - TypeScript and React ranges
How can the creator link this skill?
Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.
<a href="https://skillzs.dev/skills/arraydude/agent-skills/react-query-best-practices">View react-query-best-practices on skillZs</a>