tanstack-query

TanStack Query v5 server state management for React. Covers query/mutation patterns, v4-to-v5 migration (object syntax, gcTime, isPending, keepPreviousData), optimistic updates via useMutationState, SSR/hydration with HydrationBoundary, infinite queries, offline/PWA support, error boundaries with throwOnError, and React 19 Suspense integration. Use when building data fetching, fixing migration errors, debugging hydration mismatches, implementing caching strategies, or configuring mutations.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "tanstack-query" with this command: npx skills add oakoss/agent-skills/oakoss-agent-skills-tanstack-query

TanStack Query

Overview

TanStack Query is an async state manager, not a data fetching library. You provide a queryFn that returns a Promise; React Query handles caching, deduplication, background updates, and stale data management.

When to use: Infinite scrolling, offline-first apps, auto-refetching on focus/reconnect, complex cache invalidation, React Native, hybrid server/client apps.

When NOT to use: Purely synchronous state (useState/Zustand), normalized GraphQL caching (Apollo/urql), server-components-only apps (native fetch), simple fetch-and-display (server components).

Quick Reference

PatternAPIKey Points
Basic queryuseQuery({ queryKey, queryFn })Include params in queryKey
Suspense queryuseSuspenseQuery(options)No enabled option allowed
Parallel queriesuseQueries({ queries, combine })Dynamic parallel fetching
Dependent queryuseQuery({ enabled: !!dep })Wait for prerequisite data
Query optionsqueryOptions({ queryKey, queryFn })Reusable, type-safe config
Basic mutationuseMutation({ mutationFn, onSuccess })Invalidate on success
Mutation stateuseMutationState({ filters, select })Cross-component mutation tracking
Optimistic updateonMutate -> cancel -> snapshot -> setRollback in onError
Infinite queryuseInfiniteQuery({ initialPageParam })initialPageParam required in v5
PrefetchqueryClient.prefetchQuery(options)Preload on hover/intent
InvalidationqueryClient.invalidateQueries({ queryKey })Fuzzy-matches by default, active only
CancellationqueryFn: ({ signal }) => fetch(url, { signal })Auto-cancel on key change
Select transformselect: (data) => data.filter(...)Structural sharing preserved
Skip tokenqueryFn: id ? () => fetch(id) : skipTokenType-safe conditional disabling
Serial mutationsuseMutation({ scope: { id } })Same scope ID runs mutations in serial

v5 Migration Quick Reference

v4 (Removed)v5 (Use Instead)
useQuery(key, fn, opts)useQuery({ queryKey, queryFn, ...opts })
cacheTimegcTime
isLoading (no data)isPending
keepPreviousData: trueplaceholderData: keepPreviousData
onSuccess/onError on queriesuseEffect or mutation callbacks
useErrorBoundarythrowOnError
No initialPageParaminitialPageParam required
Error type unknownError type defaults to Error

Common Mistakes

MistakeCorrect Pattern
Checking isPending before dataData-first: check data -> error -> isPending
Copying server state to local useStateUse data directly or derived state pattern
Creating QueryClient in componentCreate once outside component or in useState
Using refetch() for parameter changesInclude params in queryKey, let it refetch automatically
Same key for useQuery and useInfiniteQueryUse distinct key segments (different cache structures)
Inline select without memoizationExtract to stable function or useCallback
Using catch without re-throwingThrow errors in queryFn (fetch doesn't reject on 4xx/5xx)
Manual generics on useQueryType the queryFn return, let inference work
Destructuring query for type narrowingKeep query object intact for proper narrowing
Using enabled with useSuspenseQueryUse conditional rendering to mount/unmount component
Not awaiting prefetch for SSRAwait prefetchQuery to avoid hydration mismatches
invalidateQueries not refetching allUse refetchType: 'all' for inactive queries

Delegation

  • Query pattern discovery: Use Explore agent
  • Cache strategy review: Use Task agent
  • Code review: Delegate to code-reviewer agent

If the tanstack-router skill is available, delegate route loader and preloading patterns to it. If the tanstack-form skill is available, delegate form submission and mutation coordination to it. If the tanstack-table skill is available, delegate server-side table patterns to it. If the tanstack-start skill is available, delegate server functions and SSR data loading to it. If the tanstack-devtools skill is available, delegate query cache debugging and inspection to it. If the tanstack-db skill is available, delegate reactive client-side database and live query patterns to it. If the tanstack-virtual skill is available, delegate list virtualization and infinite scroll rendering to it. If the tanstack-store skill is available, delegate shared client-side reactive state management to it. If the electricsql skill is available, delegate ElectricSQL real-time Postgres sync patterns to it. If the local-first skill is available, delegate local-first architecture decisions and sync engine selection to it.

References

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Automation

playwright

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

ui-ux-polish

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

tanstack-form

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

find-skills

No summary provided by upstream source.

Repository SourceNeeds Review