agentleFS
SparduttiSpardutti/claude-skills/skills/tanstack-query/SKILL.md

tanstack-query

Skill3 starsChanged 3 months agoMITView on GitHub

MUST USE when writing any @tanstack/react-query code (TanStack Query, formerly React Query), including useQuery, useMutation, useInfiniteQuery, useSuspenseQuery, useQueries, QueryClient setup, designing query keys or key factories, invalidating or prefetching cache, doing optimistic or pessimistic mutations, configuring select/error handling/retry/refetchType, or migrating from v4 to v5. Enforces v5 single-object signatures, the pending/isLoading rename, gcTime over cacheTime, serializable query keys, queryFn throwing on error, pessimistic-first mutation strategy, the cancelQueries → snapshot → setQueryData → rollback → invalidate template, refetchType: 'none' for broad invalidation, and the @lukemorales/query-key-factory merge pattern.

7 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

7 rules. 0 are common, 2 are distinctive, and 5 are very specific to this project.

  • 0

    Common

    Most of the 7 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Every hook takes one options object.

    line 28
  2. Distinctive:

    Every mount and window focus refetches.

    line 68
  3. Very specific:

    Always thread signal to fetch so the cache can cancel in-flight requests.

    line 140
  4. Very specific:

    Default to pessimistic mutations: Wait for the server, then setQueryData or invalidateQueries.

    line 204
  5. Very specific:

    One factory per domain, then mergeQueryKeys: Do not build a single 1000-line monolith.

    line 205
  6. Very specific:

    SSR: create a fresh QueryClient per request on the server, and on the client create it inside useState(() => new QueryClient()) — never at …

    line 207
  7. Very specific:

    Devtools: import @tanstack/react-query-devtools only in development (dynamic import or NODE_ENV guard) to keep the prod bundle clean.

    line 208

“Common” is measured: kept by at least 6 in 10 of the 7 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

TanStack Query — Cache, Queries, Mutations

Server-state caching for React. v5 syntax throughout. The 80% case lives in this file; deep dives in the reference files.

Quick Reference — When to Load What

Working on…Read
Designing query keys, factories, fuzzy invalidation prefixesQUERY-KEYS.md
Mutations, pessimistic vs optimistic, refetchType, post-write invalidationMUTATIONS.md
select, error handling, useInfiniteQuery, useSuspenseQuery, devtools, stale closuresQUERIES.md

Critical Gotchas (Always-Inline)

These are the bugs that ship to production silently. v5 changed a lot — most of these bite people coming from React Query v4.

1. v5 Single-Object Signatures

Every hook takes one options object. Positional args are gone.

// BAD: v4 positional — TypeScript error in v5
useQuery(['todos'], fetchTodos, { staleTime: 60_000 });
useMutation(updateTodo, { onSuccess });

// GOOD: v5
useQuery({ queryKey: ['todos'], queryFn: fetchTodos, staleTime: 60_000 });
useMutation({ mutationFn: updateTodo, onSuccess });

2. pending Replaced loading; isLoading Changed Meaning

// BAD: v4 status value
if (query.status === 'loading') return <Spinner />;

// GOOD: v5
if (query.status === 'pending') return <Spinner />;
// or
if (query.isPending) return <Spinner />;

isPending = old isLoading (no data yet). New isLoading = isPending && isFetching — true only when the first fetch is in flight. Use isPending for the initial-render spinner.

3. cacheTime Renamed to gcTime

// BAD
new QueryClient({ defaultOptions: { queries: { cacheTime: 600_000 } } });

// GOOD
new QueryClient({ defaultOptions: { queries: { gcTime: 600_000 } } });

gcTime is how long unused data lingers before garbage collection (default 5min). It does not control freshness — staleTime does.

4. staleTime: 0 Default Causes Refetch Thrash

Every mount and window focus refetches. Most apps want 30s–5min.

// GOOD: set once on the client, override per-query when needed
new QueryClient({
  defaultOptions: { queries: { staleTime: 60_000 } },
});

5. onSuccess / onError Removed From useQuery

// BAD: silently ignored in v5
useQuery({ queryKey: ['user'], queryFn: getUser, onSuccess: (u) => track(u) });

// GOOD: side effects belong in mutations or effects
const { data } = useQuery({ queryKey: ['user'], queryFn: getUser });
useEffect(() => { if (data) track(data); }, [data]);

Callbacks are still valid on useMutation.

6. useInfiniteQuery Requires initialPageParam

// BAD: v5 throws at runtime
useInfiniteQuery({
  queryKey: ['feed'],
  queryFn: ({ pageParam }) => fetchFeed(pageParam),
  getNextPageParam: (last) => last.nextCursor,
});

// GOOD
useInfiniteQuery({
  queryKey: ['feed'],
  queryFn: ({ pageParam }) => fetchFeed(pageParam),
  initialPageParam: 0,
  getNextPageParam: (last) => last.nextCursor ?? undefined,
});

7. Query Keys Must Be Serializable

Arrays of primitives + plain objects only. No Date, Map, Set, class instances, or functions. Object key order does not matter — deep-equal compared.

// BAD: Date is not serializable for the cache key
useQuery({ queryKey: ['report', new Date()], queryFn: getReport });

// GOOD
useQuery({ queryKey: ['report', date.toISOString()], queryFn: getReport });

8. queryFn Must Throw on Error

The cache treats a resolved promise as success — returning an error object hides failures.

// BAD: query stays in 'success' with bogus data
queryFn: async () => {
  const res = await fetch('/api/todos');
  return res.json();   // 4xx/5xx still resolves
};

// GOOD
queryFn: async ({ signal }) => {
  const res = await fetch('/api/todos', { signal });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
};

Always thread signal to fetch so the cache can cancel in-flight requests.

9. enabled: false Is NOT "Idle"

A disabled query sits in status: 'pending' forever with no data. Don't gate spinners on isPending alone.

// BAD: spinner shown forever when userId is undefined
const q = useQuery({ queryKey: ['user', userId], queryFn: () => getUser(userId!), enabled: !!userId });
if (q.isPending) return <Spinner />;

// GOOD: check the gate explicitly, or use fetchStatus
if (!userId) return <SignInPrompt />;
if (q.isPending) return <Spinner />;

fetchStatus === 'idle' + isPending distinguishes disabled from in-flight.

10. placeholderData: keepPreviousData Replaced keepPreviousData: true

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

// BAD: v4 syntax — ignored in v5
useQuery({ queryKey: ['todos', page], queryFn, keepPreviousData: true });

// GOOD
useQuery({ queryKey: ['todos', page], queryFn, placeholderData: keepPreviousData });

11. Fuzzy Invalidation Matches Prefixes

invalidateQueries({ queryKey: ['todos'] }) busts every key starting with ['todos', ...]. Usually what you want — pair with exact: true when you don't.

qc.invalidateQueries({ queryKey: ['todos'] });               // all todo queries
qc.invalidateQueries({ queryKey: ['todos', id], exact: true }); // only this one

When to Use What

DecisionUse
Read data in a componentuseQuery
Read data and integrate with <Suspense>useSuspenseQuery (no enabled, no isPending)
Parallel reads, variable countuseQueries({ queries: [...] })
Paginated/cursor listsuseInfiniteQuery with initialPageParam
Write datauseMutation
Refresh after a write — server is source of truthqueryClient.invalidateQueries
Refresh after a write — mutation returns fresh entityqueryClient.setQueryData (skip the refetch)
Common pattern after a writesetQueryData(detail) + invalidateQueries(list._def)
Evict on logoutqueryClient.removeQueries (or queryClient.clear())
Disable until args readyenabled: false on useQuery (never on useSuspenseQuery)
Stable spinner across page changesplaceholderData: keepPreviousData
SSRprefetchQuery + dehydrate + <HydrationBoundary>, new QueryClient per request
Devtools@tanstack/react-query-devtools, import behind a dev check

Rules

  1. v5 only: single-object signatures, pending not loading, gcTime not cacheTime, isPending for the first-fetch spinner, placeholderData: keepPreviousData over the old flag.
  2. Set staleTime on the client. The default of 0 thrashes; pick a project-wide floor (30s–5min) and override per-hook only when needed.
  3. Query keys are serializable arrays, broad to narrow: ['todos', 'list', { filters }], ['todos', 'detail', id]. Stringify dates; never put functions, Map/Set, or class instances in a key.
  4. queryFn throws on non-OK responses. Resolved promise = success in the cache. Always thread signal for cancellation.
  5. No side effects in useQuery. onSuccess/onError are gone — put effects in useEffect or in the relevant useMutation.
  6. Default to pessimistic mutations. Wait for the server, then setQueryData or invalidateQueries. Reach for optimistic only when latency hurts UX — and then all five steps: cancelQueries → snapshot → setQueryData → onError rollback → onSettled invalidate. See MUTATIONS.md.
  7. One factory per domain, then mergeQueryKeys. Do not build a single 1000-line monolith. See QUERY-KEYS.md.
  8. enabled: false is not idle. Gate UI on the precondition itself, not on isPending. Never combine enabled with useSuspenseQuery.
  9. SSR: create a fresh QueryClient per request on the server, and on the client create it inside useState(() => new QueryClient()) — never at module scope.
  10. Devtools: import @tanstack/react-query-devtools only in development (dynamic import or NODE_ENV guard) to keep the prod bundle clean.

Reference Files

For deeper guidance, load the file matching what you're working on:

  • QUERY-KEYS.md — read before your first useQuery in a repo — it may already have a key factory you must extend — and when designing query keys, building a @lukemorales/query-key-factory factory, or invalidating cache by prefix. Covers the merge pattern (one createQueryKeys file per domain, composed via mergeQueryKeys), the _def / _ctx / contextQueries shapes, fuzzy vs exact invalidation targets, and inferQueryKeys for type extraction.
  • MUTATIONS.md — read when writing useMutation, doing optimistic updates, or invalidating after a write. Covers the mutate vs mutateAsync choice, the onMutate → mutationFn → onSuccess/onError → onSettled lifecycle, pessimistic vs optimistic — pick the default, the canonical cancelQueries → snapshot → setQueryData → rollback → invalidate template, the full refetchType table (including 'none' for broad invalidations), call-site vs hook-level callbacks, and concurrent-mutation scope.
  • QUERIES.md — read when reading data, tuning options, handling errors, or integrating devtools. Covers select for derived state and re-render stability, error handling (throwOnError, retry, retryDelay, error boundaries), full useInfiniteQuery example + key-change reset gotcha, useSuspenseQuery and useQueries examples, stale closures in queryFn, network/focus options (networkMode, dev-mode refetchOnWindowFocus, gcTime: 0), and Devtools setup.

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.