react-query-best-practices
Skill2 starsChanged 3 days agoMITView on GitHub
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.
3 other projects use a version of this.
Adopted by
Most recently taken up by
- Ame-Al/ametheir own version, first seen Oct 8, 2026
- simstudioai/simtheir own version, first seen Oct 8, 2026
- bibektimilsina00/runmycrewtheir own version, first seen May 19, 2026
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- simstudioai/sim★ 30ksame name
- Ame-Al/ame★ 1same name
- bibektimilsina00/runmycrew★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository11 other files it gives its agents.
- skills/feature-workflow/AGENTS.mdAGENTS.md
- skills/react-query-best-practices/AGENTS.mdAGENTS.md
- smc-crt-analysisAGENTS.md
- skills/validate-pr/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- babysit-prSkill
- feature-workflowSkill
- qa-verifySkill
- react-query-migrate-v5Skill
- smc-crt-analysisSkill
- validate-prSkill
The file
We split this skill into the rules it gives an agent
4 rules. 0 are common, 1 is distinctive, and 3 are very specific to this project.
0
Common
Most of the 3 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 19
Read the installed version from the lockfile entry for @tanstack/react-query (the package.json range can lie).
- Very specific: line 26
Only the v3 package react-query present → these rules don't apply.
- Distinctive: line 35
Server state stays in the cache: Keep it out of client-state stores.
- Very specific: line 37
Query keys are dependencies: every variable the queryFn reads goes in the key.
“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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
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
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.

