@punks/cli 2.1.7 → 2.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +2 -2
  2. package/dist/data/AGENTS.md +3 -1
  3. package/dist/data/catalog/hooks.ts +8 -0
  4. package/dist/data/catalog/lint.ts +28 -82
  5. package/dist/data/catalog/packs.ts +8 -6
  6. package/dist/data/catalog/skills.ts +48 -0
  7. package/dist/data/catalog/tools.ts +9 -1
  8. package/dist/data/hooks/format-edited-file.mjs +1 -1
  9. package/dist/data/hooks/scaffold-update-check.mjs +181 -0
  10. package/dist/data/hooks.test.ts +19 -2
  11. package/dist/data/scripts/sync-subagents.mjs +70 -37
  12. package/dist/data/subagents/manifest.mjs +120 -0
  13. package/dist/index.js +1916 -767
  14. package/dist/skills/agnostic/cli/dp-cli/SKILL.md +3 -3
  15. package/dist/skills/agnostic/cli/dp-cli/references/commands.md +1 -1
  16. package/dist/skills/agnostic/docs/docs-onboarding/SKILL.md +46 -0
  17. package/dist/skills/agnostic/docs/docs-onboarding/agents/openai.yaml +4 -0
  18. package/dist/skills/agnostic/docs/docs-onboarding/references/artifact-contract.md +67 -0
  19. package/dist/skills/agnostic/docs/upstream/mattpocock-writing-skills.md +41 -0
  20. package/dist/skills/agnostic/docs/writing-beats/SKILL.md +69 -0
  21. package/dist/skills/agnostic/docs/writing-fragments/SKILL.md +76 -0
  22. package/dist/skills/agnostic/docs/writing-shape/SKILL.md +75 -0
  23. package/dist/skills/agnostic/planning/create-plan/SKILL.md +17 -2
  24. package/dist/skills/agnostic/planning/create-plan/references/planner-phase.md +1 -1
  25. package/dist/skills/agnostic/planning/create-spec/SKILL.md +57 -12
  26. package/dist/skills/agnostic/planning/create-spec/references/backlog-sync.md +5 -2
  27. package/dist/skills/agnostic/planning/create-spec/references/discovery.md +24 -16
  28. package/dist/skills/agnostic/planning/create-spec/references/folder-naming.md +6 -2
  29. package/dist/skills/agnostic/planning/create-spec/references/wiki-bookkeeping.md +29 -5
  30. package/dist/skills/agnostic/planning/implement-spec/SKILL.md +34 -7
  31. package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +32 -9
  32. package/dist/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +4 -2
  33. package/dist/skills/agnostic/planning/implement-spec/references/parallel.md +3 -3
  34. package/dist/skills/agnostic/planning/implement-spec/references/sequential.md +16 -6
  35. package/dist/skills/agnostic/planning/stack/SKILL.md +89 -0
  36. package/dist/skills/agnostic/quality/autoreview/SKILL.md +191 -0
  37. package/dist/skills/agnostic/quality/autoreview/scripts/autoreview +1176 -0
  38. package/dist/skills/agnostic/quality/autoreview/scripts/test-review-harness +176 -0
  39. package/dist/skills/agnostic/requirements/write-backlog/SKILL.md +7 -5
  40. package/dist/skills/frameworks/tanstack-query/tanstack-query/SKILL.md +621 -830
  41. package/dist/skills/frameworks/tanstack-start/tanstack-start/SKILL.md +250 -0
  42. package/dist/skills/phases/delivery-phase/SKILL.md +6 -1
  43. package/dist/skills/phases/docs-ingest-phase/SKILL.md +28 -20
  44. package/dist/skills/phases/docs-ingest-phase/references/fumadocs-routing.md +8 -5
  45. package/dist/skills/phases/docs-ingest-phase/references/public-docs.md +82 -0
  46. package/dist/skills/phases/requirements-phase/SKILL.md +2 -0
  47. package/dist/skills/phases/review-phase/SKILL.md +26 -9
  48. package/package.json +1 -1
@@ -1,1058 +1,849 @@
1
1
  ---
2
2
  name: tanstack-query
3
- description: |
4
- Manage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions.
5
-
6
- Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
7
- user-invocable: true
8
- ---
9
-
10
- # TanStack Query (React Query) v5
11
-
12
- **Last Updated**: 2026-01-20
13
- **Versions**: @tanstack/react-query@5.90.19, @tanstack/react-query-devtools@5.91.2
14
- **Requires**: React 18.0+ (useSyncExternalStore), TypeScript 4.7+ (recommended)
15
-
3
+ description: Powerful asynchronous state management, server-state utilities, and data fetching for TS/JS, React, Vue, Solid, Svelte & Angular.
16
4
  ---
17
5
 
18
- ## v5 New Features
19
-
20
- ### useMutationState - Cross-Component Mutation Tracking
21
6
 
22
- Access mutation state from anywhere without prop drilling:
7
+ ## Overview
23
8
 
24
- ```tsx
25
- import { useMutationState } from '@tanstack/react-query'
9
+ TanStack Query (formerly React Query) manages server state - data that lives on the server and needs to be fetched, cached, synchronized, and updated. It provides automatic caching, background refetching, stale-while-revalidate patterns, pagination, infinite scrolling, and optimistic updates out of the box.
26
10
 
27
- function GlobalLoadingIndicator() {
28
- // Get all pending mutations
29
- const pendingMutations = useMutationState({
30
- filters: { status: 'pending' },
31
- select: (mutation) => mutation.state.variables,
32
- })
11
+ **Package:** `@tanstack/react-query`
12
+ **Devtools:** `@tanstack/react-query-devtools`
13
+ **Current Version:** v5
33
14
 
34
- if (pendingMutations.length === 0) return null
35
- return <div>Saving {pendingMutations.length} items...</div>
36
- }
15
+ ## Installation
37
16
 
38
- // Filter by mutation key
39
- const todoMutations = useMutationState({
40
- filters: { mutationKey: ['addTodo'] },
41
- })
17
+ ```bash
18
+ npm install @tanstack/react-query
19
+ npm install -D @tanstack/react-query-devtools # Optional
42
20
  ```
43
21
 
44
- ### Simplified Optimistic Updates
45
-
46
- New pattern using `variables` - no cache manipulation, no rollback needed:
22
+ ## Setup
47
23
 
48
24
  ```tsx
49
- function TodoList() {
50
- const { data: todos } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
25
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
26
+ import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
51
27
 
52
- const addTodo = useMutation({
53
- mutationKey: ['addTodo'],
54
- mutationFn: (newTodo) => api.addTodo(newTodo),
55
- onSuccess: () => {
56
- queryClient.invalidateQueries({ queryKey: ['todos'] })
28
+ const queryClient = new QueryClient({
29
+ defaultOptions: {
30
+ queries: {
31
+ staleTime: 1000 * 60, // 1 minute
32
+ gcTime: 1000 * 60 * 5, // 5 minutes (garbage collection)
33
+ retry: 3,
34
+ refetchOnWindowFocus: true,
35
+ refetchOnReconnect: true,
57
36
  },
58
- })
59
-
60
- // Show optimistic UI using variables from pending mutations
61
- const pendingTodos = useMutationState({
62
- filters: { mutationKey: ['addTodo'], status: 'pending' },
63
- select: (mutation) => mutation.state.variables,
64
- })
37
+ },
38
+ })
65
39
 
40
+ function App() {
66
41
  return (
67
- <ul>
68
- {todos?.map(todo => <li key={todo.id}>{todo.title}</li>)}
69
- {/* Show pending items with visual indicator */}
70
- {pendingTodos.map((todo, i) => (
71
- <li key={`pending-${i}`} style={{ opacity: 0.5 }}>{todo.title}</li>
72
- ))}
73
- </ul>
42
+ <QueryClientProvider client={queryClient}>
43
+ <YourApp />
44
+ <ReactQueryDevtools initialIsOpen={false} />
45
+ </QueryClientProvider>
74
46
  )
75
47
  }
76
48
  ```
77
49
 
78
- ### throwOnError - Error Boundaries
50
+ ## Core Concepts
51
+
52
+ ### Query Keys
79
53
 
80
- Renamed from `useErrorBoundary` (breaking change):
54
+ Query keys uniquely identify cached data. They must be serializable arrays:
81
55
 
82
56
  ```tsx
83
- import { QueryErrorResetBoundary } from '@tanstack/react-query'
84
- import { ErrorBoundary } from 'react-error-boundary'
57
+ // Simple key
58
+ useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
85
59
 
86
- function App() {
87
- return (
88
- <QueryErrorResetBoundary>
89
- {({ reset }) => (
90
- <ErrorBoundary onReset={reset} fallbackRender={({ resetErrorBoundary }) => (
91
- <div>
92
- Error! <button onClick={resetErrorBoundary}>Retry</button>
93
- </div>
94
- )}>
95
- <Todos />
96
- </ErrorBoundary>
97
- )}
98
- </QueryErrorResetBoundary>
99
- )
100
- }
60
+ // With variables (dependency array pattern)
61
+ useQuery({ queryKey: ['todos', { status, page }], queryFn: fetchTodos })
101
62
 
102
- function Todos() {
103
- const { data } = useQuery({
104
- queryKey: ['todos'],
105
- queryFn: fetchTodos,
106
- throwOnError: true, // ✅ v5 (was useErrorBoundary in v4)
107
- })
108
- return <div>{data.map(...)}</div>
109
- }
110
- ```
63
+ // Hierarchical keys for invalidation
64
+ useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodo(todoId) })
65
+ useQuery({ queryKey: ['todos', todoId, 'comments'], queryFn: () => fetchComments(todoId) })
111
66
 
112
- ### Network Mode (Offline/PWA Support)
67
+ // Invalidation matches prefixes:
68
+ // queryClient.invalidateQueries({ queryKey: ['todos'] })
69
+ // ^ Invalidates ALL queries starting with 'todos'
70
+ ```
113
71
 
114
- Control behavior when offline:
72
+ ### Query Functions
115
73
 
116
74
  ```tsx
117
- const queryClient = new QueryClient({
118
- defaultOptions: {
119
- queries: {
120
- networkMode: 'offlineFirst', // Use cache when offline
121
- },
75
+ // Query function receives a QueryFunctionContext
76
+ useQuery({
77
+ queryKey: ['todos', todoId],
78
+ queryFn: async ({ queryKey, signal, meta }) => {
79
+ const [_key, id] = queryKey
80
+ const response = await fetch(`/api/todos/${id}`, { signal })
81
+ if (!response.ok) throw new Error('Failed to fetch')
82
+ return response.json()
122
83
  },
123
84
  })
124
85
 
125
- // Per-query override
86
+ // Using the signal for automatic cancellation
126
87
  useQuery({
127
88
  queryKey: ['todos'],
128
- queryFn: fetchTodos,
129
- networkMode: 'always', // Always try, even offline (for local APIs)
89
+ queryFn: async ({ signal }) => {
90
+ const response = await fetch('/api/todos', { signal })
91
+ return response.json()
92
+ },
130
93
  })
131
94
  ```
132
95
 
133
- | Mode | Behavior |
134
- |------|----------|
135
- | `online` (default) | Only fetch when online |
136
- | `always` | Always try (useful for local/service worker APIs) |
137
- | `offlineFirst` | Use cache first, fetch when online |
138
-
139
- **Detecting paused state:**
140
- ```tsx
141
- const { isPending, fetchStatus } = useQuery(...)
142
- // isPending + fetchStatus === 'paused' = offline, waiting for network
143
- ```
144
-
145
- ### useQueries with Combine
96
+ ### queryOptions Helper
146
97
 
147
- Combine results from parallel queries:
98
+ Create reusable, type-safe query configurations:
148
99
 
149
100
  ```tsx
150
- const results = useQueries({
151
- queries: userIds.map(id => ({
152
- queryKey: ['user', id],
153
- queryFn: () => fetchUser(id),
154
- })),
155
- combine: (results) => ({
156
- data: results.map(r => r.data),
157
- pending: results.some(r => r.isPending),
158
- error: results.find(r => r.error)?.error,
159
- }),
101
+ import { queryOptions } from '@tanstack/react-query'
102
+
103
+ export const todosQueryOptions = queryOptions({
104
+ queryKey: ['todos'],
105
+ queryFn: fetchTodos,
106
+ staleTime: 5000,
160
107
  })
161
108
 
162
- // Access combined result
163
- if (results.pending) return <Loading />
164
- console.log(results.data) // [user1, user2, user3]
109
+ export const todoQueryOptions = (todoId: string) =>
110
+ queryOptions({
111
+ queryKey: ['todos', todoId],
112
+ queryFn: () => fetchTodo(todoId),
113
+ enabled: !!todoId,
114
+ })
115
+
116
+ // Usage
117
+ const { data } = useQuery(todosQueryOptions)
118
+ const { data } = useSuspenseQuery(todoQueryOptions(id))
119
+ await queryClient.prefetchQuery(todosQueryOptions)
165
120
  ```
166
121
 
167
- ### infiniteQueryOptions Helper
122
+ ## Queries (useQuery)
168
123
 
169
- Type-safe factory for infinite queries (parallel to `queryOptions`):
124
+ ### Basic Usage
170
125
 
171
126
  ```tsx
172
- import { infiniteQueryOptions, useInfiniteQuery, prefetchInfiniteQuery } from '@tanstack/react-query'
127
+ import { useQuery } from '@tanstack/react-query'
173
128
 
174
- const todosInfiniteOptions = infiniteQueryOptions({
175
- queryKey: ['todos', 'infinite'],
176
- queryFn: ({ pageParam }) => fetchTodosPage(pageParam),
177
- initialPageParam: 0,
178
- getNextPageParam: (lastPage) => lastPage.nextCursor,
179
- })
129
+ function Todos() {
130
+ const {
131
+ data,
132
+ error,
133
+ isLoading, // First load, no data yet
134
+ isFetching, // Any fetch in progress (including background)
135
+ isError,
136
+ isSuccess,
137
+ isPending, // No data yet (same as isLoading in most cases)
138
+ status, // 'pending' | 'error' | 'success'
139
+ fetchStatus, // 'fetching' | 'paused' | 'idle'
140
+ refetch,
141
+ isStale,
142
+ isPlaceholderData,
143
+ dataUpdatedAt,
144
+ errorUpdatedAt,
145
+ } = useQuery({
146
+ queryKey: ['todos'],
147
+ queryFn: fetchTodos,
148
+ })
180
149
 
181
- // Reuse across hooks
182
- useInfiniteQuery(todosInfiniteOptions)
183
- useSuspenseInfiniteQuery(todosInfiniteOptions)
184
- prefetchInfiniteQuery(queryClient, todosInfiniteOptions)
150
+ if (isLoading) return <Spinner />
151
+ if (isError) return <Error message={error.message} />
152
+ return <TodoList todos={data} />
153
+ }
185
154
  ```
186
155
 
187
- ### maxPages - Memory Optimization
188
-
189
- Limit pages stored in cache for infinite queries:
156
+ ### Query Options
190
157
 
191
158
  ```tsx
192
- useInfiniteQuery({
193
- queryKey: ['posts'],
194
- queryFn: ({ pageParam }) => fetchPosts(pageParam),
195
- initialPageParam: 0,
196
- getNextPageParam: (lastPage) => lastPage.nextCursor,
197
- getPreviousPageParam: (firstPage) => firstPage.prevCursor, // Required with maxPages
198
- maxPages: 3, // Only keep 3 pages in memory
199
- })
200
- ```
159
+ useQuery({
160
+ queryKey: ['todos'],
161
+ queryFn: fetchTodos,
201
162
 
202
- **Note:** `maxPages` requires bi-directional pagination (`getNextPageParam` AND `getPreviousPageParam`).
163
+ // Freshness
164
+ staleTime: 5000, // ms data stays fresh (default: 0)
165
+ gcTime: 300000, // ms unused data stays in cache (default: 5 min)
203
166
 
204
- ---
167
+ // Refetching
168
+ refetchInterval: 10000, // Poll every 10s
169
+ refetchIntervalInBackground: false, // Don't poll when tab hidden
170
+ refetchOnMount: true, // Refetch on component mount if stale
171
+ refetchOnWindowFocus: true, // Refetch on window focus if stale
172
+ refetchOnReconnect: true, // Refetch on network reconnect
205
173
 
206
- ## Quick Setup
174
+ // Retry
175
+ retry: 3, // Number of retries (or function)
176
+ retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
207
177
 
208
- ```bash
209
- npm install @tanstack/react-query@latest
210
- npm install -D @tanstack/react-query-devtools@latest
211
- ```
178
+ // Conditional
179
+ enabled: !!userId, // Only run when truthy
212
180
 
213
- ### Step 2: Provider + Config
181
+ // Initial/placeholder data
182
+ initialData: () => cachedData,
183
+ initialDataUpdatedAt: Date.now() - 10000,
184
+ placeholderData: (previousData) => previousData, // keepPreviousData pattern
185
+ placeholderData: initialTodos,
214
186
 
215
- ```tsx
216
- // src/main.tsx
217
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
218
- import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
187
+ // Transform
188
+ select: (data) => data.filter(todo => !todo.done),
219
189
 
220
- const queryClient = new QueryClient({
221
- defaultOptions: {
222
- queries: {
223
- staleTime: 1000 * 60 * 5, // 5 min
224
- gcTime: 1000 * 60 * 60, // 1 hour (v5: renamed from cacheTime)
225
- refetchOnWindowFocus: false,
226
- },
227
- },
228
- })
190
+ // Structural sharing (default: true)
191
+ structuralSharing: true,
229
192
 
230
- <QueryClientProvider client={queryClient}>
231
- <App />
232
- <ReactQueryDevtools initialIsOpen={false} />
233
- </QueryClientProvider>
234
- ```
193
+ // Network mode
194
+ networkMode: 'online', // 'online' | 'always' | 'offlineFirst'
235
195
 
236
- ### Step 3: Query + Mutation Hooks
196
+ // Meta (accessible in query function context)
197
+ meta: { purpose: 'user-facing' },
198
+ })
199
+ ```
237
200
 
238
- ```tsx
239
- // src/hooks/useTodos.ts
240
- import { useQuery, useMutation, useQueryClient, queryOptions } from '@tanstack/react-query'
201
+ ## Mutations (useMutation)
241
202
 
242
- // Query options factory (v5 pattern)
243
- export const todosQueryOptions = queryOptions({
244
- queryKey: ['todos'],
245
- queryFn: async () => {
246
- const res = await fetch('/api/todos')
247
- if (!res.ok) throw new Error('Failed to fetch')
248
- return res.json()
249
- },
250
- })
203
+ ### Basic Usage
251
204
 
252
- export function useTodos() {
253
- return useQuery(todosQueryOptions)
254
- }
205
+ ```tsx
206
+ import { useMutation, useQueryClient } from '@tanstack/react-query'
255
207
 
256
- export function useAddTodo() {
208
+ function AddTodo() {
257
209
  const queryClient = useQueryClient()
258
- return useMutation({
259
- mutationFn: async (newTodo) => {
260
- const res = await fetch('/api/todos', {
210
+
211
+ const mutation = useMutation({
212
+ mutationFn: (newTodo: { title: string }) => {
213
+ return fetch('/api/todos', {
261
214
  method: 'POST',
262
- headers: { 'Content-Type': 'application/json' },
263
215
  body: JSON.stringify(newTodo),
264
- })
265
- if (!res.ok) throw new Error('Failed to add')
266
- return res.json()
216
+ }).then(res => res.json())
217
+ },
218
+ // Lifecycle callbacks
219
+ onMutate: async (variables) => {
220
+ // Called before mutationFn
221
+ // Good for optimistic updates
222
+ return { previousTodos } // context for onError
267
223
  },
268
- onSuccess: () => {
224
+ onSuccess: (data, variables, context) => {
225
+ // Invalidate related queries
226
+ queryClient.invalidateQueries({ queryKey: ['todos'] })
227
+ },
228
+ onError: (error, variables, context) => {
229
+ // Rollback optimistic updates
230
+ queryClient.setQueryData(['todos'], context.previousTodos)
231
+ },
232
+ onSettled: (data, error, variables, context) => {
233
+ // Always runs (success or error)
269
234
  queryClient.invalidateQueries({ queryKey: ['todos'] })
270
235
  },
271
236
  })
272
- }
273
-
274
- // Usage:
275
- function TodoList() {
276
- const { data, isPending, isError, error } = useTodos()
277
- const { mutate } = useAddTodo()
278
237
 
279
- if (isPending) return <div>Loading...</div>
280
- if (isError) return <div>Error: {error.message}</div>
281
- return <ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
238
+ return (
239
+ <button
240
+ onClick={() => mutation.mutate({ title: 'New Todo' })}
241
+ disabled={mutation.isPending}
242
+ >
243
+ {mutation.isPending ? 'Adding...' : 'Add Todo'}
244
+ </button>
245
+ )
282
246
  }
283
247
  ```
284
248
 
285
- ---
286
-
287
- ## Critical Rules
288
-
289
- ### Always Do
290
-
291
- ✅ **Use object syntax for all hooks**
292
- ```tsx
293
- // v5 ONLY supports this:
294
- useQuery({ queryKey, queryFn, ...options })
295
- useMutation({ mutationFn, ...options })
296
- ```
297
-
298
- ✅ **Use array query keys**
299
- ```tsx
300
- queryKey: ['todos'] // List
301
- queryKey: ['todos', id] // Detail
302
- queryKey: ['todos', { filter }] // Filtered
303
- ```
249
+ ### Mutation State
304
250
 
305
- ✅ **Configure staleTime appropriately**
306
251
  ```tsx
307
- staleTime: 1000 * 60 * 5 // 5 min - prevents excessive refetches
252
+ const {
253
+ mutate, // Fire-and-forget
254
+ mutateAsync, // Returns promise
255
+ isPending, // Mutation in progress
256
+ isError,
257
+ isSuccess,
258
+ isIdle, // Not yet fired
259
+ data, // Success response
260
+ error, // Error object
261
+ reset, // Reset state to idle
262
+ variables, // Variables passed to mutate
263
+ status, // 'idle' | 'pending' | 'error' | 'success'
264
+ } = useMutation({ ... })
308
265
  ```
309
266
 
310
- ✅ **Use isPending for initial loading state**
311
- ```tsx
312
- if (isPending) return <Loading />
313
- // isPending = no data yet AND fetching
314
- ```
267
+ ## Optimistic Updates
315
268
 
316
- ✅ **Throw errors in queryFn**
317
269
  ```tsx
318
- if (!response.ok) throw new Error('Failed')
319
- ```
270
+ const mutation = useMutation({
271
+ mutationFn: updateTodo,
272
+ onMutate: async (newTodo) => {
273
+ // 1. Cancel outgoing refetches
274
+ await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
320
275
 
321
- ✅ **Invalidate queries after mutations**
322
- ```tsx
323
- onSuccess: () => {
324
- queryClient.invalidateQueries({ queryKey: ['todos'] })
325
- }
326
- ```
276
+ // 2. Snapshot previous value
277
+ const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
327
278
 
328
- ✅ **Use queryOptions factory for reusable patterns**
329
- ```tsx
330
- const opts = queryOptions({ queryKey, queryFn })
331
- useQuery(opts)
332
- useSuspenseQuery(opts)
333
- prefetchQuery(opts)
334
- ```
279
+ // 3. Optimistically update
280
+ queryClient.setQueryData(['todos', newTodo.id], newTodo)
335
281
 
336
- ✅ **Use gcTime (not cacheTime)**
337
- ```tsx
338
- gcTime: 1000 * 60 * 60 // 1 hour
282
+ // 4. Return context for rollback
283
+ return { previousTodo }
284
+ },
285
+ onError: (err, newTodo, context) => {
286
+ // Rollback on error
287
+ queryClient.setQueryData(['todos', newTodo.id], context.previousTodo)
288
+ },
289
+ onSettled: () => {
290
+ // Always refetch to sync with server
291
+ queryClient.invalidateQueries({ queryKey: ['todos'] })
292
+ },
293
+ })
339
294
  ```
340
295
 
341
- ### Never Do
342
-
343
- ❌ **Never use v4 array/function syntax**
344
- ```tsx
345
- // v4 (removed in v5):
346
- useQuery(['todos'], fetchTodos, options) // ❌
347
-
348
- // v5 (correct):
349
- useQuery({ queryKey: ['todos'], queryFn: fetchTodos }) // ✅
350
- ```
296
+ ### Optimistic Updates on Lists
351
297
 
352
- ❌ **Never use query callbacks (onSuccess, onError, onSettled in queries)**
353
298
  ```tsx
354
- // v5 removed these from queries:
355
- useQuery({
356
- queryKey: ['todos'],
357
- queryFn: fetchTodos,
358
- onSuccess: (data) => {}, // ❌ Removed in v5
359
- })
299
+ onMutate: async (newTodo) => {
300
+ await queryClient.cancelQueries({ queryKey: ['todos'] })
301
+ const previousTodos = queryClient.getQueryData(['todos'])
360
302
 
361
- // Use useEffect instead:
362
- const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
363
- useEffect(() => {
364
- if (data) {
365
- // Do something
366
- }
367
- }, [data])
368
-
369
- // Or use mutation callbacks (still supported):
370
- useMutation({
371
- mutationFn: addTodo,
372
- onSuccess: () => {}, // ✅ Still works for mutations
373
- })
374
- ```
303
+ queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
375
304
 
376
- ❌ **Never use deprecated options**
377
- ```tsx
378
- // Deprecated in v5:
379
- cacheTime: 1000 // ❌ Use gcTime instead
380
- isLoading: true // ❌ Meaning changed, use isPending
381
- keepPreviousData: true // ❌ Use placeholderData instead
382
- onSuccess: () => {} // ❌ Removed from queries
383
- useErrorBoundary: true // ❌ Use throwOnError instead
305
+ return { previousTodos }
306
+ },
307
+ onError: (err, newTodo, context) => {
308
+ queryClient.setQueryData(['todos'], context.previousTodos)
309
+ },
384
310
  ```
385
311
 
386
- ❌ **Never assume isLoading means "no data yet"**
387
- ```tsx
388
- // v5 changed this:
389
- isLoading = isPending && isFetching // ❌ Now means "pending AND fetching"
390
- isPending = no data yet // ✅ Use this for initial load
391
- ```
312
+ ## Query Invalidation
392
313
 
393
- ❌ **Never forget initialPageParam for infinite queries**
394
314
  ```tsx
395
- // v5 requires this:
396
- useInfiniteQuery({
397
- queryKey: ['projects'],
398
- queryFn: ({ pageParam }) => fetchProjects(pageParam),
399
- initialPageParam: 0, // ✅ Required in v5
400
- getNextPageParam: (lastPage) => lastPage.nextCursor,
401
- })
402
- ```
315
+ const queryClient = useQueryClient()
403
316
 
404
- ❌ **Never use enabled with useSuspenseQuery**
405
- ```tsx
406
- // Not allowed:
407
- useSuspenseQuery({
408
- queryKey: ['todo', id],
409
- queryFn: () => fetchTodo(id),
410
- enabled: !!id, // ❌ Not available with suspense
411
- })
317
+ // Invalidate all queries
318
+ queryClient.invalidateQueries()
412
319
 
413
- // Use conditional rendering instead:
414
- {id && <TodoComponent id={id} />}
415
- ```
320
+ // Invalidate by prefix
321
+ queryClient.invalidateQueries({ queryKey: ['todos'] })
416
322
 
417
- ❌ **Never rely on refetchOnMount: false for errored queries**
418
- ```tsx
419
- // Doesn't work - errors are always stale
420
- useQuery({
421
- queryKey: ['data'],
422
- queryFn: failingFetch,
423
- refetchOnMount: false, // ❌ Ignored when query has error
424
- })
323
+ // Invalidate exact match
324
+ queryClient.invalidateQueries({ queryKey: ['todos', 1], exact: true })
425
325
 
426
- // Use retryOnMount instead
427
- useQuery({
428
- queryKey: ['data'],
429
- queryFn: failingFetch,
430
- refetchOnMount: false,
431
- retryOnMount: false, // ✅ Prevents refetch for errored queries
432
- retry: 0,
326
+ // Invalidate with predicate
327
+ queryClient.invalidateQueries({
328
+ predicate: (query) =>
329
+ query.queryKey[0] === 'todos' && query.queryKey[1]?.status === 'done',
433
330
  })
434
- ```
435
331
 
436
- ---
332
+ // Invalidate and refetch immediately
333
+ queryClient.refetchQueries({ queryKey: ['todos'] })
437
334
 
438
- ## Known Issues Prevention
335
+ // Remove from cache entirely
336
+ queryClient.removeQueries({ queryKey: ['todos', 1] })
439
337
 
440
- This skill prevents **16 documented issues** from v5 migration, SSR/hydration bugs, and common mistakes:
338
+ // Reset to initial state
339
+ queryClient.resetQueries({ queryKey: ['todos'] })
340
+ ```
441
341
 
442
- ### Issue #1: Object Syntax Required
443
- **Error**: `useQuery is not a function` or type errors
444
- **Source**: [v5 Migration Guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#removed-overloads-in-favor-of-object-syntax)
445
- **Why It Happens**: v5 removed all function overloads, only object syntax works
446
- **Prevention**: Always use `useQuery({ queryKey, queryFn, ...options })`
342
+ ## Infinite Queries
447
343
 
448
- **Before (v4):**
449
344
  ```tsx
450
- useQuery(['todos'], fetchTodos, { staleTime: 5000 })
451
- ```
345
+ import { useInfiniteQuery } from '@tanstack/react-query'
452
346
 
453
- **After (v5):**
454
- ```tsx
455
- useQuery({
456
- queryKey: ['todos'],
457
- queryFn: fetchTodos,
458
- staleTime: 5000
459
- })
347
+ function InfiniteList() {
348
+ const {
349
+ data,
350
+ fetchNextPage,
351
+ fetchPreviousPage,
352
+ hasNextPage,
353
+ hasPreviousPage,
354
+ isFetchingNextPage,
355
+ isFetchingPreviousPage,
356
+ } = useInfiniteQuery({
357
+ queryKey: ['projects'],
358
+ queryFn: async ({ pageParam }) => {
359
+ const res = await fetch(`/api/projects?cursor=${pageParam}`)
360
+ return res.json()
361
+ },
362
+ initialPageParam: 0,
363
+ getNextPageParam: (lastPage, allPages, lastPageParam) => {
364
+ return lastPage.nextCursor ?? undefined // undefined = no more pages
365
+ },
366
+ getPreviousPageParam: (firstPage, allPages, firstPageParam) => {
367
+ return firstPage.prevCursor ?? undefined
368
+ },
369
+ maxPages: 3, // Keep max 3 pages in cache (for performance)
370
+ })
371
+
372
+ return (
373
+ <div>
374
+ {data.pages.map((page) =>
375
+ page.items.map((item) => <Item key={item.id} item={item} />)
376
+ )}
377
+ <button
378
+ onClick={() => fetchNextPage()}
379
+ disabled={!hasNextPage || isFetchingNextPage}
380
+ >
381
+ {isFetchingNextPage ? 'Loading...' : hasNextPage ? 'Load More' : 'No more'}
382
+ </button>
383
+ </div>
384
+ )
385
+ }
460
386
  ```
461
387
 
462
- ### Issue #2: Query Callbacks Removed
463
- **Error**: Callbacks don't run, TypeScript errors
464
- **Source**: [v5 Breaking Changes](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#callbacks-on-usequery-and-queryobserver-have-been-removed)
465
- **Why It Happens**: onSuccess, onError, onSettled removed from queries (still work in mutations)
466
- **Prevention**: Use `useEffect` for side effects, or move logic to mutation callbacks
388
+ ## Parallel Queries
467
389
 
468
- **Before (v4):**
469
390
  ```tsx
470
- useQuery({
471
- queryKey: ['todos'],
472
- queryFn: fetchTodos,
473
- onSuccess: (data) => {
474
- console.log('Todos loaded:', data)
475
- },
476
- })
477
- ```
391
+ // Multiple independent queries run in parallel automatically
392
+ function Dashboard() {
393
+ const usersQuery = useQuery({ queryKey: ['users'], queryFn: fetchUsers })
394
+ const projectsQuery = useQuery({ queryKey: ['projects'], queryFn: fetchProjects })
478
395
 
479
- **After (v5):**
480
- ```tsx
481
- const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
482
- useEffect(() => {
483
- if (data) {
484
- console.log('Todos loaded:', data)
485
- }
486
- }, [data])
396
+ // Both fetch simultaneously
397
+ }
398
+
399
+ // Dynamic parallel queries with useQueries
400
+ function UserProjects({ userIds }) {
401
+ const queries = useQueries({
402
+ queries: userIds.map((id) => ({
403
+ queryKey: ['user', id],
404
+ queryFn: () => fetchUser(id),
405
+ })),
406
+ combine: (results) => ({
407
+ data: results.map(r => r.data),
408
+ pending: results.some(r => r.isPending),
409
+ }),
410
+ })
411
+ }
487
412
  ```
488
413
 
489
- ### Issue #3: Status Loading → Pending
490
- **Error**: UI shows wrong loading state
491
- **Source**: [v5 Migration: isLoading renamed](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#isloading-and-isfetching-flags)
492
- **Why It Happens**: `status: 'loading'` renamed to `status: 'pending'`, `isLoading` meaning changed
493
- **Prevention**: Use `isPending` for initial load, `isLoading` for "pending AND fetching"
414
+ ## Dependent Queries
494
415
 
495
- **Before (v4):**
496
416
  ```tsx
497
- const { data, isLoading } = useQuery(...)
498
- if (isLoading) return <div>Loading...</div>
499
- ```
417
+ // Sequential queries using enabled
418
+ function UserPosts({ userId }) {
419
+ const userQuery = useQuery({
420
+ queryKey: ['user', userId],
421
+ queryFn: () => fetchUser(userId),
422
+ })
500
423
 
501
- **After (v5):**
502
- ```tsx
503
- const { data, isPending, isLoading } = useQuery(...)
504
- if (isPending) return <div>Loading...</div>
505
- // isLoading = isPending && isFetching (fetching for first time)
424
+ const postsQuery = useQuery({
425
+ queryKey: ['posts', userId],
426
+ queryFn: () => fetchPostsByUser(userId),
427
+ enabled: !!userQuery.data, // Only run when user is loaded
428
+ })
429
+ }
506
430
  ```
507
431
 
508
- ### Issue #4: cacheTime → gcTime
509
- **Error**: `cacheTime is not a valid option`
510
- **Source**: [v5 Migration: gcTime](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#cachetime-has-been-replaced-by-gctime)
511
- **Why It Happens**: Renamed to better reflect "garbage collection time"
512
- **Prevention**: Use `gcTime` instead of `cacheTime`
432
+ ## Paginated Queries
513
433
 
514
- **Before (v4):**
515
434
  ```tsx
516
- useQuery({
517
- queryKey: ['todos'],
518
- queryFn: fetchTodos,
519
- cacheTime: 1000 * 60 * 60,
520
- })
521
- ```
435
+ function PaginatedList() {
436
+ const [page, setPage] = useState(1)
522
437
 
523
- **After (v5):**
524
- ```tsx
525
- useQuery({
526
- queryKey: ['todos'],
527
- queryFn: fetchTodos,
528
- gcTime: 1000 * 60 * 60,
529
- })
438
+ const { data, isPlaceholderData } = useQuery({
439
+ queryKey: ['todos', page],
440
+ queryFn: () => fetchTodos(page),
441
+ placeholderData: (previousData) => previousData, // Keep showing old data
442
+ })
443
+
444
+ return (
445
+ <div style={{ opacity: isPlaceholderData ? 0.5 : 1 }}>
446
+ {data.items.map(item => <Item key={item.id} item={item} />)}
447
+ <button
448
+ onClick={() => setPage(p => p + 1)}
449
+ disabled={isPlaceholderData || !data.hasMore}
450
+ >
451
+ Next
452
+ </button>
453
+ </div>
454
+ )
455
+ }
530
456
  ```
531
457
 
532
- ### Issue #5: useSuspenseQuery + enabled
533
- **Error**: Type error, enabled option not available
534
- **Source**: [GitHub Discussion #6206](https://github.com/TanStack/query/discussions/6206)
535
- **Why It Happens**: Suspense guarantees data is available, can't conditionally disable
536
- **Prevention**: Use conditional rendering instead of `enabled` option
458
+ ## Suspense Integration
537
459
 
538
- **Before (v4/incorrect):**
539
460
  ```tsx
540
- useSuspenseQuery({
541
- queryKey: ['todo', id],
542
- queryFn: () => fetchTodo(id),
543
- enabled: !!id, // ❌ Not allowed
544
- })
545
- ```
461
+ import { useSuspenseQuery, useSuspenseInfiniteQuery } from '@tanstack/react-query'
546
462
 
547
- **After (v5/correct):**
548
- ```tsx
549
- // Conditional rendering:
550
- {id ? (
551
- <TodoComponent id={id} />
552
- ) : (
553
- <div>No ID selected</div>
554
- )}
555
-
556
- // Inside TodoComponent:
557
- function TodoComponent({ id }: { id: number }) {
463
+ // Component will suspend until data is loaded
464
+ function TodoList() {
558
465
  const { data } = useSuspenseQuery({
559
- queryKey: ['todo', id],
560
- queryFn: () => fetchTodo(id),
561
- // No enabled option needed
466
+ queryKey: ['todos'],
467
+ queryFn: fetchTodos,
562
468
  })
563
- return <div>{data.title}</div>
469
+ // data is guaranteed to be defined here
470
+ return <ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
564
471
  }
565
- ```
566
472
 
567
- ### Issue #6: initialPageParam Required
568
- **Error**: `initialPageParam is required` type error
569
- **Source**: [v5 Migration: Infinite Queries](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#new-required-initialPageParam-option)
570
- **Why It Happens**: v4 passed `undefined` as first pageParam, v5 requires explicit value
571
- **Prevention**: Always specify `initialPageParam` for infinite queries
572
-
573
- **Before (v4):**
574
- ```tsx
575
- useInfiniteQuery({
576
- queryKey: ['projects'],
577
- queryFn: ({ pageParam = 0 }) => fetchProjects(pageParam),
578
- getNextPageParam: (lastPage) => lastPage.nextCursor,
579
- })
580
- ```
473
+ // Wrap with Suspense boundary
474
+ function App() {
475
+ return (
476
+ <ErrorBoundary fallback={<Error />}>
477
+ <Suspense fallback={<Loading />}>
478
+ <TodoList />
479
+ </Suspense>
480
+ </ErrorBoundary>
481
+ )
482
+ }
581
483
 
582
- **After (v5):**
583
- ```tsx
584
- useInfiniteQuery({
585
- queryKey: ['projects'],
586
- queryFn: ({ pageParam }) => fetchProjects(pageParam),
587
- initialPageParam: 0, // ✅ Required
588
- getNextPageParam: (lastPage) => lastPage.nextCursor,
589
- })
484
+ // Multiple suspense queries (fetch in parallel)
485
+ function Dashboard() {
486
+ const [{ data: users }, { data: projects }] = useSuspenseQueries({
487
+ queries: [
488
+ { queryKey: ['users'], queryFn: fetchUsers },
489
+ { queryKey: ['projects'], queryFn: fetchProjects },
490
+ ],
491
+ })
492
+ }
590
493
  ```
591
494
 
592
- ### Issue #7: keepPreviousData Removed
593
- **Error**: `keepPreviousData is not a valid option`
594
- **Source**: [v5 Migration: placeholderData](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#removed-keeppreviousdata-in-favor-of-placeholderdata-identity-function)
595
- **Why It Happens**: Replaced with more flexible `placeholderData` function
596
- **Prevention**: Use `placeholderData: keepPreviousData` helper
597
-
598
- **Before (v4):**
599
- ```tsx
600
- useQuery({
601
- queryKey: ['todos', page],
602
- queryFn: () => fetchTodos(page),
603
- keepPreviousData: true,
604
- })
605
- ```
495
+ ## Prefetching
606
496
 
607
- **After (v5):**
608
497
  ```tsx
609
- import { keepPreviousData } from '@tanstack/react-query'
498
+ const queryClient = useQueryClient()
610
499
 
611
- useQuery({
612
- queryKey: ['todos', page],
613
- queryFn: () => fetchTodos(page),
614
- placeholderData: keepPreviousData,
615
- })
616
- ```
500
+ // Prefetch on hover
501
+ function TodoLink({ todoId }) {
502
+ const prefetch = () => {
503
+ queryClient.prefetchQuery({
504
+ queryKey: ['todo', todoId],
505
+ queryFn: () => fetchTodo(todoId),
506
+ staleTime: 5000, // Only prefetch if data older than 5s
507
+ })
508
+ }
617
509
 
618
- ### Issue #8: TypeScript Error Type Default
619
- **Error**: Type errors with error handling
620
- **Source**: [v5 Migration: Error Types](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#typeerror-is-now-the-default-error)
621
- **Why It Happens**: v4 used `unknown`, v5 defaults to `Error` type
622
- **Prevention**: If throwing non-Error types, specify error type explicitly
510
+ return (
511
+ <Link to={`/todos/${todoId}`} onMouseEnter={prefetch}>
512
+ Todo {todoId}
513
+ </Link>
514
+ )
515
+ }
623
516
 
624
- **Before (v4 - error was unknown):**
625
- ```tsx
626
- const { error } = useQuery({
627
- queryKey: ['data'],
628
- queryFn: async () => {
629
- if (Math.random() > 0.5) throw 'custom error string'
630
- return data
631
- },
517
+ // Prefetch in route loader (TanStack Router integration)
518
+ export const Route = createFileRoute('/todos/$todoId')({
519
+ loader: ({ context: { queryClient }, params: { todoId } }) =>
520
+ queryClient.ensureQueryData(todoQueryOptions(todoId)),
632
521
  })
633
- // error: unknown
634
- ```
635
522
 
636
- **After (v5 - specify custom error type):**
637
- ```tsx
638
- const { error } = useQuery<DataType, string>({
639
- queryKey: ['data'],
640
- queryFn: async () => {
641
- if (Math.random() > 0.5) throw 'custom error string'
642
- return data
643
- },
644
- })
645
- // error: string | null
646
-
647
- // Or better: always throw Error objects
648
- const { error } = useQuery({
649
- queryKey: ['data'],
650
- queryFn: async () => {
651
- if (Math.random() > 0.5) throw new Error('custom error')
652
- return data
653
- },
523
+ // Prefetch infinite queries
524
+ queryClient.prefetchInfiniteQuery({
525
+ queryKey: ['projects'],
526
+ queryFn: fetchProjects,
527
+ initialPageParam: 0,
528
+ pages: 3, // Prefetch first 3 pages
654
529
  })
655
- // error: Error | null (default)
656
530
  ```
657
531
 
658
- ### Issue #9: Streaming Server Components Hydration Error
659
- **Error**: `Hydration failed because the initial UI does not match what was rendered on the server`
660
- **Source**: [GitHub Issue #9642](https://github.com/TanStack/query/issues/9642)
661
- **Affects**: v5.82.0+ with streaming SSR (void prefetch pattern)
662
- **Why It Happens**: Race condition where `hydrate()` resolves synchronously but `query.fetch()` creates async retryer, causing isFetching/isStale mismatch between server and client
663
- **Prevention**: Don't conditionally render based on `fetchStatus` with `useSuspenseQuery` and streaming prefetch, OR await prefetch instead of void pattern
664
-
665
- **Before (causes hydration error):**
666
- ```tsx
667
- // Server: void prefetch
668
- streamingQueryClient.prefetchQuery({ queryKey: ['data'], queryFn: getData });
532
+ ## SSR & Hydration
669
533
 
670
- // Client: conditional render on fetchStatus
671
- const { data, isFetching } = useSuspenseQuery({ queryKey: ['data'], queryFn: getData });
672
- return <>{data && <div>{data}</div>} {isFetching && <Loading />}</>;
673
- ```
534
+ ### Server-Side Prefetching
674
535
 
675
- **After (workaround):**
676
536
  ```tsx
677
- // Option 1: Await prefetch
678
- await streamingQueryClient.prefetchQuery({ queryKey: ['data'], queryFn: getData });
679
-
680
- // Option 2: Don't render based on fetchStatus with Suspense
681
- const { data } = useSuspenseQuery({ queryKey: ['data'], queryFn: getData });
682
- return <div>{data}</div>; // No conditional on isFetching
683
- ```
684
-
685
- **Status**: Known issue, being investigated by maintainers. Requires implementation of `getServerSnapshot` in useSyncExternalStore.
537
+ // Server component or loader
538
+ import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
686
539
 
687
- ### Issue #10: useQuery Hydration Error with Prefetching
688
- **Error**: Text content mismatch during hydration
689
- **Source**: [GitHub Issue #9399](https://github.com/TanStack/query/issues/9399)
690
- **Affects**: v5.x with server-side prefetching
691
- **Why It Happens**: `tryResolveSync` detects resolved promises in RSC payload and extracts data synchronously during hydration, bypassing normal pending state
692
- **Prevention**: Use `useSuspenseQuery` instead of `useQuery` for SSR, or avoid conditional rendering based on `isLoading`
540
+ async function getServerSideProps() {
541
+ const queryClient = new QueryClient()
693
542
 
694
- **Before (causes hydration error):**
695
- ```tsx
696
- // Server Component
697
- const queryClient = getServerQueryClient();
698
- await queryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos });
543
+ await queryClient.prefetchQuery({
544
+ queryKey: ['todos'],
545
+ queryFn: fetchTodos,
546
+ })
699
547
 
700
- // Client Component
701
- function Todos() {
702
- const { data, isLoading } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });
703
- if (isLoading) return <div>Loading...</div>; // Server renders this
704
- return <div>{data.length} todos</div>; // Client hydrates with this
548
+ return {
549
+ props: {
550
+ dehydratedState: dehydrate(queryClient),
551
+ },
552
+ }
705
553
  }
706
- ```
707
554
 
708
- **After (workaround):**
709
- ```tsx
710
- // Use useSuspenseQuery instead
711
- function Todos() {
712
- const { data } = useSuspenseQuery({ queryKey: ['todos'], queryFn: fetchTodos });
713
- return <div>{data.length} todos</div>;
555
+ function Page({ dehydratedState }) {
556
+ return (
557
+ <HydrationBoundary state={dehydratedState}>
558
+ <Todos />
559
+ </HydrationBoundary>
560
+ )
714
561
  }
715
562
  ```
716
563
 
717
- **Status**: "At the top of my OSS list of things to fix" - maintainer Ephem (Nov 2025). Requires implementing `getServerSnapshot` in useSyncExternalStore.
718
-
719
- ### Issue #11: refetchOnMount Not Respected for Errored Queries
720
- **Error**: Queries refetch on mount despite `refetchOnMount: false`
721
- **Source**: [GitHub Issue #10018](https://github.com/TanStack/query/issues/10018)
722
- **Affects**: v5.90.16+
723
- **Why It Happens**: Errored queries with no data are always treated as stale. This is intentional to avoid permanently showing error states
724
- **Prevention**: Use `retryOnMount: false` instead of (or in addition to) `refetchOnMount: false`
725
-
726
- **Before (refetches despite setting):**
727
- ```tsx
728
- const { data, error } = useQuery({
729
- queryKey: ['data'],
730
- queryFn: () => { throw new Error('Fails') },
731
- refetchOnMount: false, // Ignored when query is in error state
732
- retry: 0,
733
- });
734
- // Query refetches every time component mounts
735
- ```
564
+ ### Streaming SSR (React Server Components)
736
565
 
737
- **After (correct):**
738
566
  ```tsx
739
- const { data, error } = useQuery({
740
- queryKey: ['data'],
741
- queryFn: failingFetch,
742
- refetchOnMount: false,
743
- retryOnMount: false, // ✅ Prevents refetch on mount for errored queries
744
- retry: 0,
745
- });
746
- ```
567
+ import { dehydrate, HydrationBoundary } from '@tanstack/react-query'
568
+ import { makeQueryClient } from './query-client'
747
569
 
748
- **Status**: Documented behavior (intentional). The name `retryOnMount` is slightly misleading - it controls whether errored queries trigger a new fetch on mount, not automatic retries.
570
+ export default async function Page() {
571
+ const queryClient = makeQueryClient()
749
572
 
750
- ### Issue #12: Mutation Callback Signature Breaking Change (v5.89.0)
751
- **Error**: TypeScript errors in mutation callbacks
752
- **Source**: [GitHub Issue #9660](https://github.com/TanStack/query/issues/9660)
753
- **Affects**: v5.89.0+
754
- **Why It Happens**: `onMutateResult` parameter added between `variables` and `context`, changing callback signatures from 3 params to 4
755
- **Prevention**: Update all mutation callbacks to accept 4 parameters instead of 3
573
+ // Prefetch on server
574
+ await queryClient.prefetchQuery({
575
+ queryKey: ['todos'],
576
+ queryFn: fetchTodos,
577
+ })
756
578
 
757
- **Before (v5.88 and earlier):**
758
- ```tsx
759
- useMutation({
760
- mutationFn: addTodo,
761
- onError: (error, variables, context) => {
762
- // context is now onMutateResult, missing final context param
763
- },
764
- onSuccess: (data, variables, context) => {
765
- // Same issue
766
- }
767
- });
579
+ return (
580
+ <HydrationBoundary state={dehydrate(queryClient)}>
581
+ <TodoList />
582
+ </HydrationBoundary>
583
+ )
584
+ }
768
585
  ```
769
586
 
770
- **After (v5.89.0+):**
771
- ```tsx
772
- useMutation({
773
- mutationFn: addTodo,
774
- onError: (error, variables, onMutateResult, context) => {
775
- // onMutateResult = return value from onMutate
776
- // context = mutation function context
777
- },
778
- onSuccess: (data, variables, onMutateResult, context) => {
779
- // Correct signature with 4 parameters
780
- }
781
- });
782
- ```
587
+ ## QueryClient API
783
588
 
784
- **Note**: If you don't use `onMutate`, the `onMutateResult` parameter will be undefined. This breaking change was introduced in a patch version.
589
+ ```tsx
590
+ const queryClient = useQueryClient()
785
591
 
786
- ### Issue #13: Readonly Query Keys Break Partial Matching (v5.90.8)
787
- **Error**: `Type 'readonly ["todos", string]' is not assignable to type '["todos", string]'`
788
- **Source**: [GitHub Issue #9871](https://github.com/TanStack/query/issues/9871) | Fixed in [PR #9872](https://github.com/TanStack/query/pull/9872)
789
- **Affects**: v5.90.8 only (fixed in v5.90.9)
790
- **Why It Happens**: Partial query matching broke TypeScript types for readonly query keys (using `as const`)
791
- **Prevention**: Upgrade to v5.90.9+ or use type assertions if stuck on v5.90.8
592
+ // Get cached data
593
+ queryClient.getQueryData(['todos'])
792
594
 
793
- **Before (v5.90.8 - TypeScript error):**
794
- ```tsx
795
- export function todoQueryKey(id?: string) {
796
- return id ? ['todos', id] as const : ['todos'] as const;
797
- }
798
- // Type: readonly ['todos', string] | readonly ['todos']
799
-
800
- useMutation({
801
- mutationFn: addTodo,
802
- onSuccess: () => {
803
- queryClient.invalidateQueries({
804
- queryKey: todoQueryKey('123')
805
- // Error: readonly ['todos', string] not assignable to ['todos', string]
806
- });
807
- }
808
- });
809
- ```
595
+ // Set cached data
596
+ queryClient.setQueryData(['todos'], updatedTodos)
597
+ queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
810
598
 
811
- **After (v5.90.9+):**
812
- ```tsx
813
- // Works correctly with readonly types
814
- queryClient.invalidateQueries({
815
- queryKey: todoQueryKey('123') // ✅ No type error
816
- });
817
- ```
599
+ // Get query state
600
+ queryClient.getQueryState(['todos'])
818
601
 
819
- **Status**: Fixed in v5.90.9. Particularly affected users of code generators like `openapi-react-query` that produce readonly query keys.
602
+ // Check if fetching
603
+ queryClient.isFetching({ queryKey: ['todos'] })
604
+ queryClient.isMutating()
820
605
 
821
- ### Issue #14: useMutationState Type Inference Lost
822
- **Error**: `mutation.state.variables` typed as `unknown` instead of actual type
823
- **Source**: [GitHub Issue #9825](https://github.com/TanStack/query/issues/9825)
824
- **Affects**: All v5.x versions
825
- **Why It Happens**: Fuzzy mutation key matching prevents guaranteed type inference (same issue as `queryClient.getQueryCache().find()`)
826
- **Prevention**: Explicitly cast types in the `select` callback
606
+ // Cancel queries
607
+ queryClient.cancelQueries({ queryKey: ['todos'] })
827
608
 
828
- **Before (type inference doesn't work):**
829
- ```tsx
830
- const addTodo = useMutation({
831
- mutationKey: ['addTodo'],
832
- mutationFn: (todo: Todo) => api.addTodo(todo),
833
- });
834
-
835
- const pendingTodos = useMutationState({
836
- filters: { mutationKey: ['addTodo'], status: 'pending' },
837
- select: (mutation) => {
838
- return mutation.state.variables; // Type: unknown
839
- },
840
- });
841
- ```
609
+ // Invalidate (marks stale, refetches active)
610
+ queryClient.invalidateQueries({ queryKey: ['todos'] })
842
611
 
843
- **After (with explicit cast):**
844
- ```tsx
845
- const pendingTodos = useMutationState({
846
- filters: { mutationKey: ['addTodo'], status: 'pending' },
847
- select: (mutation) => mutation.state.variables as Todo,
848
- });
849
- // Or cast the entire state:
850
- select: (mutation) => mutation.state as MutationState<Todo, Error, Todo, unknown>
851
- ```
612
+ // Refetch (force refetch even if fresh)
613
+ queryClient.refetchQueries({ queryKey: ['todos'] })
852
614
 
853
- **Status**: Known limitation of fuzzy matching. No planned fix.
615
+ // Remove from cache
616
+ queryClient.removeQueries({ queryKey: ['todos'] })
854
617
 
855
- ### Issue #15: Query Cancellation in StrictMode with fetchQuery
856
- **Error**: `CancelledError` when using `fetchQuery()` with `useQuery`
857
- **Source**: [GitHub Issue #9798](https://github.com/TanStack/query/issues/9798)
858
- **Affects**: Development only (React StrictMode)
859
- **Why It Happens**: StrictMode causes double mount/unmount. When `useQuery` unmounts and is the last observer, it cancels the query even if `fetchQuery()` is also running
860
- **Prevention**: This is expected development-only behavior. Doesn't affect production
618
+ // Reset to initial state
619
+ queryClient.resetQueries({ queryKey: ['todos'] })
861
620
 
862
- **Example:**
863
- ```tsx
864
- async function loadData() {
865
- try {
866
- const data = await queryClient.fetchQuery({
867
- queryKey: ['data'],
868
- queryFn: fetchData,
869
- });
870
- console.log('Loaded:', data); // Never logs in StrictMode
871
- } catch (error) {
872
- console.error('Failed:', error); // CancelledError
873
- }
874
- }
621
+ // Clear entire cache
622
+ queryClient.clear()
875
623
 
876
- function Component() {
877
- const { data } = useQuery({ queryKey: ['data'], queryFn: fetchData });
878
- // In StrictMode, component unmounts/remounts, cancelling fetchQuery
879
- }
880
- ```
624
+ // Prefetch
625
+ queryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos })
626
+ queryClient.ensureQueryData({ queryKey: ['todos'], queryFn: fetchTodos })
881
627
 
882
- **Workaround:**
883
- ```tsx
884
- // Keep query observed with staleTime
885
- const { data } = useQuery({
886
- queryKey: ['data'],
887
- queryFn: fetchData,
888
- staleTime: Infinity, // Keeps query active
889
- });
628
+ // Get/set defaults
629
+ queryClient.setQueryDefaults(['todos'], { staleTime: 10000 })
630
+ queryClient.getQueryDefaults(['todos'])
631
+ queryClient.setMutationDefaults(['addTodo'], { mutationFn: addTodo })
890
632
  ```
891
633
 
892
- **Status**: Expected StrictMode behavior, not a bug. Production builds are unaffected.
893
-
894
- ### Issue #16: invalidateQueries Only Refetches Active Queries
895
- **Error**: Inactive queries not refetching despite `invalidateQueries()` call
896
- **Source**: [GitHub Issue #9531](https://github.com/TanStack/query/issues/9531)
897
- **Affects**: All v5.x versions
898
- **Why It Happens**: Documentation was misleading - `invalidateQueries()` only refetches "active" queries by default, not "all" queries
899
- **Prevention**: Use `refetchType: 'all'` to force refetch of inactive queries
634
+ ## Testing
900
635
 
901
- **Default behavior:**
902
636
  ```tsx
903
- // Only active queries (currently being observed) will refetch
904
- queryClient.invalidateQueries({ queryKey: ['todos'] });
905
- ```
637
+ import { renderHook, waitFor } from '@testing-library/react'
638
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
906
639
 
907
- **To refetch inactive queries:**
908
- ```tsx
909
- queryClient.invalidateQueries({
910
- queryKey: ['todos'],
911
- refetchType: 'all' // Refetch active AND inactive
912
- });
913
- ```
640
+ function createWrapper() {
641
+ const queryClient = new QueryClient({
642
+ defaultOptions: {
643
+ queries: {
644
+ retry: false, // Don't retry in tests
645
+ gcTime: Infinity, // Prevent garbage collection during tests
646
+ },
647
+ },
648
+ })
649
+ return ({ children }) => (
650
+ <QueryClientProvider client={queryClient}>
651
+ {children}
652
+ </QueryClientProvider>
653
+ )
654
+ }
914
655
 
915
- **Status**: Documentation fixed to clarify "active" queries. This is the intended behavior.
656
+ test('fetches todos', async () => {
657
+ const { result } = renderHook(() => useQuery({
658
+ queryKey: ['todos'],
659
+ queryFn: fetchTodos,
660
+ }), { wrapper: createWrapper() })
916
661
 
917
- ---
662
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
663
+ expect(result.current.data).toEqual(expectedTodos)
664
+ })
918
665
 
919
- ## Community Tips
666
+ // Mock with setQueryData for component tests
667
+ test('renders todos', () => {
668
+ const queryClient = new QueryClient()
669
+ queryClient.setQueryData(['todos'], mockTodos)
920
670
 
921
- > **Note**: These tips come from community experts and maintainer blogs. Verify against your version.
671
+ render(
672
+ <QueryClientProvider client={queryClient}>
673
+ <TodoList />
674
+ </QueryClientProvider>
675
+ )
922
676
 
923
- ### Tip: Query Options with Multiple Listeners
677
+ expect(screen.getByText('Todo 1')).toBeInTheDocument()
678
+ })
679
+ ```
924
680
 
925
- **Source**: [TkDodo's Blog - API Design Lessons](https://tkdodo.eu/blog/react-query-api-design-lessons-learned) | **Confidence**: HIGH
926
- **Applies to**: v5.27.3+
681
+ ## TypeScript Patterns
927
682
 
928
- When multiple components use the same query with different options (like `staleTime`), the "last write wins" rule applies for future fetches, but the current in-flight query uses its original options. This can cause unexpected behavior when components mount at different times.
683
+ ### Typing Query Functions
929
684
 
930
- **Example of unexpected behavior:**
931
685
  ```tsx
932
- // Component A mounts first
933
- function ComponentA() {
934
- const { data } = useQuery({
935
- queryKey: ['todos'],
936
- queryFn: fetchTodos,
937
- staleTime: 5000, // Applied initially
938
- });
686
+ interface Todo {
687
+ id: number
688
+ title: string
689
+ completed: boolean
939
690
  }
940
691
 
941
- // Component B mounts while A's query is in-flight
942
- function ComponentB() {
943
- const { data } = useQuery({
944
- queryKey: ['todos'],
945
- queryFn: fetchTodos,
946
- staleTime: 60000, // Won't affect current fetch, only future ones
947
- });
948
- }
949
- ```
950
-
951
- **Recommended approach:**
952
- ```tsx
953
- // Write options as functions that reference latest values
954
- const getStaleTime = () => shouldUseLongCache ? 60000 : 5000;
692
+ // Type is inferred from queryFn return type
693
+ const { data } = useQuery({
694
+ queryKey: ['todos'],
695
+ queryFn: async (): Promise<Todo[]> => {
696
+ const res = await fetch('/api/todos')
697
+ return res.json()
698
+ },
699
+ })
700
+ // data: Todo[] | undefined
955
701
 
956
- useQuery({
702
+ // With select
703
+ const { data } = useQuery({
957
704
  queryKey: ['todos'],
958
705
  queryFn: fetchTodos,
959
- staleTime: getStaleTime(), // Evaluated on each render
960
- });
706
+ select: (data): string[] => data.map(t => t.title),
707
+ })
708
+ // data: string[] | undefined
961
709
  ```
962
710
 
963
- ### Tip: refetch() is NOT for Changed Parameters
964
-
965
- **Source**: [Avoiding Common Mistakes with TanStack Query](https://www.buncolak.com/posts/avoiding-common-mistakes-with-tanstack-query-part-1/) | **Confidence**: HIGH
966
-
967
- The `refetch()` function should ONLY be used for refreshing with the same parameters (like a manual "reload" button). For new parameters (filters, page numbers, search terms, etc.), include them in the query key instead.
968
-
969
- **Anti-pattern:**
970
- ```tsx
971
- // ❌ Wrong - using refetch() for different parameters
972
- const [page, setPage] = useState(1);
973
- const { data, refetch } = useQuery({
974
- queryKey: ['todos'], // Same key for all pages
975
- queryFn: () => fetchTodos(page),
976
- });
977
-
978
- // This refetches with OLD page value, not new one
979
- <button onClick={() => { setPage(2); refetch(); }}>Next</button>
980
- ```
711
+ ### Typing Errors
981
712
 
982
- **Correct pattern:**
983
713
  ```tsx
984
- // ✅ Correct - include parameters in query key
985
- const [page, setPage] = useState(1);
986
- const { data } = useQuery({
987
- queryKey: ['todos', page], // Key changes with page
988
- queryFn: () => fetchTodos(page),
989
- // Query automatically refetches when page changes
990
- });
714
+ // Default error type is Error
715
+ const { error } = useQuery<Todo[], AxiosError>({
716
+ queryKey: ['todos'],
717
+ queryFn: fetchTodos,
718
+ })
991
719
 
992
- <button onClick={() => setPage(2)}>Next</button> // Just update state
720
+ // Or register globally
721
+ declare module '@tanstack/react-query' {
722
+ interface Register {
723
+ defaultError: AxiosError
724
+ }
725
+ }
993
726
  ```
994
727
 
995
- **When to use refetch():**
728
+ ### Query Options Pattern (Recommended)
729
+
996
730
  ```tsx
997
- // ✅ Manual refresh of same data (refresh button)
998
- const { data, refetch } = useQuery({
999
- queryKey: ['todos'],
731
+ import { queryOptions, infiniteQueryOptions } from '@tanstack/react-query'
732
+
733
+ export const todosOptions = queryOptions({
734
+ queryKey: ['todos'] as const,
1000
735
  queryFn: fetchTodos,
1001
- });
736
+ staleTime: 5000,
737
+ })
1002
738
 
1003
- <button onClick={() => refetch()}>Refresh</button> // Same parameters
739
+ export const todoOptions = (id: string) =>
740
+ queryOptions({
741
+ queryKey: ['todos', id] as const,
742
+ queryFn: () => fetchTodo(id),
743
+ enabled: !!id,
744
+ })
745
+
746
+ // Full type inference everywhere
747
+ const { data } = useQuery(todosOptions)
748
+ const { data } = useSuspenseQuery(todoOptions('123'))
749
+ await queryClient.ensureQueryData(todosOptions)
750
+ queryClient.invalidateQueries({ queryKey: todosOptions.queryKey })
1004
751
  ```
1005
752
 
1006
- ---
753
+ ## Advanced Patterns
1007
754
 
1008
- ## Key Patterns
755
+ ### Window Focus Refetching
1009
756
 
1010
- **Dependent Queries** (Query B waits for Query A):
1011
757
  ```tsx
1012
- const { data: posts } = useQuery({
1013
- queryKey: ['users', userId, 'posts'],
1014
- queryFn: () => fetchUserPosts(userId),
1015
- enabled: !!user, // Wait for user
758
+ // Disable globally
759
+ const queryClient = new QueryClient({
760
+ defaultOptions: {
761
+ queries: { refetchOnWindowFocus: false },
762
+ },
1016
763
  })
1017
- ```
1018
764
 
1019
- **Parallel Queries** (fetch multiple at once):
1020
- ```tsx
1021
- const results = useQueries({
1022
- queries: ids.map(id => ({ queryKey: ['todos', id], queryFn: () => fetchTodo(id) })),
765
+ // Custom focus manager
766
+ import { focusManager } from '@tanstack/react-query'
767
+
768
+ // For React Native
769
+ focusManager.setEventListener((handleFocus) => {
770
+ const subscription = AppState.addEventListener('change', (state) => {
771
+ handleFocus(state === 'active')
772
+ })
773
+ return () => subscription.remove()
1023
774
  })
1024
775
  ```
1025
776
 
1026
- **Prefetching** (preload on hover):
1027
- ```tsx
1028
- queryClient.prefetchQuery({ queryKey: ['todo', id], queryFn: () => fetchTodo(id) })
1029
- ```
777
+ ### Network Mode
1030
778
 
1031
- **Infinite Scroll** (useInfiniteQuery):
1032
779
  ```tsx
1033
- useInfiniteQuery({
1034
- queryKey: ['todos', 'infinite'],
1035
- queryFn: ({ pageParam }) => fetchTodosPage(pageParam),
1036
- initialPageParam: 0, // Required in v5
1037
- getNextPageParam: (lastPage) => lastPage.nextCursor,
780
+ useQuery({
781
+ queryKey: ['todos'],
782
+ queryFn: fetchTodos,
783
+ // 'online' (default): only fetch when online
784
+ // 'always': always fetch (useful for local-first)
785
+ // 'offlineFirst': try fetch, use cache if offline
786
+ networkMode: 'offlineFirst',
1038
787
  })
1039
788
  ```
1040
789
 
1041
- **Query Cancellation** (auto-cancel on queryKey change):
790
+ ### Query Cancellation
791
+
1042
792
  ```tsx
1043
- queryFn: async ({ signal }) => {
1044
- const res = await fetch(`/api/todos?q=${search}`, { signal })
1045
- return res.json()
1046
- }
793
+ useQuery({
794
+ queryKey: ['todos'],
795
+ queryFn: async ({ signal }) => {
796
+ // signal is AbortSignal - automatically cancelled on unmount or key change
797
+ const res = await fetch('/api/todos', { signal })
798
+ return res.json()
799
+ },
800
+ })
801
+
802
+ // Manual cancellation
803
+ queryClient.cancelQueries({ queryKey: ['todos'] })
1047
804
  ```
1048
805
 
1049
- **Data Transformation** (select):
806
+ ### Persistence
807
+
1050
808
  ```tsx
1051
- select: (data) => data.filter(todo => todo.completed)
1052
- ```
809
+ import { persistQueryClient } from '@tanstack/react-query-persist-client'
810
+ import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
1053
811
 
1054
- **Avoid Request Waterfalls**: Fetch in parallel when possible (don't chain queries unless truly dependent)
812
+ const persister = createSyncStoragePersister({
813
+ storage: window.localStorage,
814
+ })
1055
815
 
1056
- ---
816
+ persistQueryClient({
817
+ queryClient,
818
+ persister,
819
+ maxAge: 1000 * 60 * 60 * 24, // 24 hours
820
+ })
821
+ ```
1057
822
 
1058
- **Official Docs**: https://tanstack.com/query/latest | **v5 Migration**: https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5 | **GitHub**: https://github.com/TanStack/query | **Source Context**: run `opensrc path @tanstack/react-query`, then inspect the returned checkout path
823
+ ## Best Practices
824
+
825
+ 1. **Use `queryOptions` helper** for type-safe, reusable query configurations
826
+ 2. **Structure query keys hierarchically** for granular invalidation
827
+ 3. **Set appropriate `staleTime`** - 0 means always refetch on mount (default), increase for less dynamic data
828
+ 4. **Use `placeholderData`** (not `initialData`) for keeping previous page data during pagination
829
+ 5. **Prefer `useSuspenseQuery`** when using Suspense boundaries for cleaner component code
830
+ 6. **Use `enabled`** for dependent queries, not conditional hook calls
831
+ 7. **Always invalidate after mutations** - don't rely solely on optimistic updates
832
+ 8. **Cancel queries in `onMutate`** before optimistic updates to prevent race conditions
833
+ 9. **Use `ensureQueryData`** in route loaders instead of `prefetchQuery` for immediate access
834
+ 10. **Set `retry: false` in tests** to avoid timeout issues
835
+ 11. **Don't destructure the query result** if you need to pass it around (breaks reactivity)
836
+ 12. **Use `select`** for derived data instead of transforming in the component
837
+ 13. **Keep query functions pure** - they should only fetch, not cause side effects
838
+ 14. **Use `gcTime: Infinity`** in tests to prevent cache cleanup during assertions
839
+
840
+ ## Common Pitfalls
841
+
842
+ - Using `initialData` when you mean `placeholderData` (initialData counts as "fresh" data)
843
+ - Not providing `initialPageParam` for infinite queries (required in v5)
844
+ - Calling hooks conditionally (violates React rules)
845
+ - Not cancelling queries before optimistic updates (race conditions)
846
+ - Setting `staleTime` higher than `gcTime` (data gets garbage collected while "fresh")
847
+ - Forgetting to wrap tests with `QueryClientProvider`
848
+ - Using same `QueryClient` instance across tests (shared state)
849
+ - Not awaiting `invalidateQueries` in mutation callbacks when order matters