Instructions
When to Use
- Use for TanStack Query v5 + RSC hydration without double fetch.
- Prefer
next-server-patternswhen the question is server-only data. - Prefer
server-caching-handbookfor tag/TTL stampedes.
Use TanStack Query v5 (@tanstack/react-query) with Next.js App Router without fighting RSC.
- Provider: wrap client subtree that needs queries - usually a
providers.tsxclient component imported fromlayout.tsx; do not wrap entire app in client unless necessary. - Keys: stable serializable arrays; include locale and filters; never embed secrets in keys.
- Server prefetch: when RSC fetches initial data, pass dehydrated state to client
HydrationBoundary+prefetchQuery- clientuseQuerymust use same key and compatiblequeryFnor rely on hydrated data. - Defaults: set sensible
staleTime(e.g. 30s–5m for dashboards); avoidrefetchOnWindowFocusstorm on sensitive forms - tune per query. - Mutations:
onSuccessinvalidate minimal key prefixes; optimistic updates only with rollback plan. - Errors: surface with boundaries (
error-loading-not-foundskill); do not leak server error bodies to toast without sanitization.
Outcomes
- Provider file outline + one
useQuery+ one RSC prefetch example names only (no full app).
Output Rules
State installed @tanstack/react-query version from lockfile; if missing, say “install v5 first” with pnpm add @tanstack/react-query.
Scope and boundaries
- In scope: Query client setup, hydration, keys, mutations, cache tuning.
- Out of scope: GraphQL client selection, tRPC (different pattern).
Safety
- No API keys in
queryFn; use server Route Handlers for secrets.
Troubleshooting
- Double fetch: RSC and client both fetch same URL - align prefetch +
initialDataor hydration only. - Stale closure in queryFn: use
queryKeydeps; avoid capturing mutable outer state without inclusion in key.
Related skills
next-server-patterns- RSC vs client fetch boundariesforms-and-validation- mutations with invalidationserver-caching-handbook- server cache vs client cache
GitHub: https://github.com/bh611627/skillcodex/tree/main/skills/client-data-fetching/SKILL.md
npm: https://www.npmjs.com/package/@skillcodex/skills