Open History to see the last commit
1'use client'
2// The development-only part of `QueryStrictMode`. Only imported behind `NODE_ENV` checks, so
3// production bundles leave this file out.
4import * as React from 'react'
5β
6import { environmentManager } from '@tanstack/query-core'
7import { useQueryClient } from './QueryClientProvider'
8import { useIsRestoring } from './IsRestoringProvider'
9import {
10 QueryStrictModeProvider,
11 useQueryStrictMode,
12} from './QueryStrictModeContext'
13import { QueryStrictModeMissingPrefetchError } from './QueryStrictModeError'
14import type {
15 Query,
16 QueryCache,
17 QueryObserverResult,
18} from '@tanstack/query-core'
19import type {
20 QueryStrictModeMissingPrefetchEvent,
21 QueryStrictModeMissingPrefetchHandler,
22 QueryStrictModeProps,
23 QueryStrictModeUnusedPrefetchEvent,
24 QueryStrictModeUnusedPrefetchHandler,
25 QueryStrictModeValue,
26} from './QueryStrictModeTypes'
27β
28// Missing prefetches cause request waterfalls, so they are thrown. Unused prefetches only waste a
29// request, so they are logged.
30const defaultHandleMissingPrefetch: QueryStrictModeMissingPrefetchHandler = (
31 event,
32) => {
33 throw new QueryStrictModeMissingPrefetchError(event)
34}
35β
36const defaultHandleUnusedPrefetch: QueryStrictModeUnusedPrefetchHandler = (
37 event,
38) => {
39 console.warn(event.message)
40}
41β
42/**
43 * Records when the data of each prefetch arrives in a `QueryCache`, starting from the first render
44 * of an outermost `QueryStrictMode`. Data can arrive before `QueryStrictMode` commits, for example
45 * while a sibling suspends, so the tracking can't wait for an effect.
46 */
47interface PrefetchTracker {
48 /**
49 * When the data of the last prefetch of each query arrived. Data from `setQueryData` and
50 * `hydrate` isn't recorded.
51 */
52 prefetches: Map<Query<any, any, any, any>, number>
53 /**
54 * The queries read by a hook inside a `QueryStrictMode`, or already reported. A query counts as
55 * used even before the reading component commits, for example while a sibling still suspends.
56 * Shared by all `QueryStrictMode`s of the cache, so each unused prefetch is reported only once.
57 */
58 used: WeakSet<Query<any, any, any, any>>
59 /**
60 * When the prefetch was recorded that each query was last checked for, so a timer that already
61 * ran doesn't start again
62 */
63 checked: WeakMap<Query<any, any, any, any>, number>
64 /**
65 * Called with a query when its prefetch is recorded, or when it is removed from the cache.
66 */
67 listeners: Set<(query: Query<any, any, any, any>) => void>
68 /**
69 * How many committed `QueryStrictMode`s use the tracker.
70 */
71 mounted: number
72 unsubscribe: () => void
73}
74β
75const prefetchTrackers = new WeakMap<QueryCache, PrefetchTracker>()
76β
77/**
78 * Gets the tracker of a `QueryCache`, and starts tracking if no `QueryStrictMode` uses it yet.
79 * @param cache - The cache to track.
80 * @returns The tracker of `cache`.
81 */
82const getPrefetchTracker = (cache: QueryCache) => {
83 let tracker = prefetchTrackers.get(cache)
84 if (!tracker) {
85 const prefetches: PrefetchTracker['prefetches'] = new Map()
86 const listeners: PrefetchTracker['listeners'] = new Set()
87 const unsubscribe = cache.subscribe((event) => {
88 if (event.type === 'removed') {
89 prefetches.delete(event.query)
90 } else if (
91 event.type === 'updated' &&
92 event.action.type === 'success' &&
93 !event.action.manual
94 ) {
95 prefetches.set(event.query, Date.now())
96 } else {
97 return
98 }
99 listeners.forEach((listener) => listener(event.query))
100 })
101 tracker = {
102 prefetches,
103 used: new WeakSet(),
104 checked: new WeakMap(),
105 listeners,
106 mounted: 0,
107 unsubscribe,
108 }
109 prefetchTrackers.set(cache, tracker)
110 }
111 return tracker
112}
113/**
114 * The development implementation of `QueryStrictMode`. Tracks prefetches for the whole cache, and
115 * shares `handleMissingPrefetch` with the hooks below it.
116 * @param props - The `children` to check, and the handlers and options passed to `QueryStrictMode`.
117 * @returns The `children`, inside the context of this `QueryStrictMode`.
118 * @throws {unknown} Whatever `handleUnusedPrefetch` throws, during the next render.
119 */
120export const DevQueryStrictMode = ({
121 children,
122 handleUnusedPrefetch = defaultHandleUnusedPrefetch,
123 unusedPrefetchTimeout = 5000,
124 queryClient,
125 ...props
126}: QueryStrictModeProps) => {
127 const client = useQueryClient(queryClient)
128 const isRestoring = useIsRestoring()
129 const parent = useQueryStrictMode()
130 const isNested = parent !== null
131 // A nested `QueryStrictMode` without its own handler keeps the one of its parent
132 const handleMissingPrefetch =
133 props.handleMissingPrefetch ??
134 parent?.handleMissingPrefetch ??
135 defaultHandleMissingPrefetch
136β
137 // Thrown during render, so it reaches the error boundary above this `QueryStrictMode`. Wrapped,
138 // so that any value thrown by `handleUnusedPrefetch` is rethrown unchanged
139 const [thrown, setThrown] = React.useState<{ error: unknown } | null>(null)
140 if (thrown) {
141 throw thrown.error
142 }
143β
144 // Tracked from the first render, so prefetches whose data arrives before the effect runs are
145 // reported too. Not on the server, where nothing reports them.
146 const cache = client.getQueryCache()
147 if (!isNested && !environmentManager.isServer()) {
148 getPrefetchTracker(cache)
149 }
150β
151 const handleUnusedPrefetchRef = React.useRef(handleUnusedPrefetch)
152 React.useEffect(() => {
153 handleUnusedPrefetchRef.current = handleUnusedPrefetch
154 }, [handleUnusedPrefetch])
155β
156 React.useEffect(() => {
157 if (isNested || isRestoring) {
158 return
159 }
160β
161 const tracker = getPrefetchTracker(cache)
162 const { used, checked } = tracker
163 const timers = new Map<
164 Query<any, any, any, any>,
165 ReturnType<typeof setTimeout>
166 >()
167β
168 const isUnused = (query: Query<any, any, any, any>) =>
169 !used.has(query) && query.getObserversCount() === 0
170β
171 // Starts a timer from when the prefetch of `query` was recorded, or clears it when `query` was
172 // removed from the cache
173 const check = (query: Query<any, any, any, any>) => {
174 const prefetchedAt = tracker.prefetches.get(query)
175 if (prefetchedAt === undefined) {
176 clearTimeout(timers.get(query))
177 timers.delete(query)
178 return
179 }
180 if (
181 timers.has(query) ||
182 checked.get(query) === prefetchedAt ||
183 !isUnused(query)
184 ) {
185 return
186 }
187 const timer = setTimeout(
188 () => {
189 timers.delete(query)
190 checked.set(query, prefetchedAt)
191 if (isUnused(query)) {
192 // Report each query only once
193 used.add(query)
194 const problem: QueryStrictModeUnusedPrefetchEvent = {
195 type: 'unused-prefetch',
196 message: `[${query.queryHash}]: The query was prefetched, but nothing used it within ${unusedPrefetchTimeout}ms. Remove the prefetch, or check that it uses the same queryKey as the query that reads it.`,
197 query,
198 }
199 try {
200 handleUnusedPrefetchRef.current(problem)
201 } catch (error) {
202 setThrown({ error })
203 }
204 }
205 },
206 Math.max(0, prefetchedAt + unusedPrefetchTimeout - Date.now()),
207 )
208 timers.set(query, timer)
209 }
210β
211 tracker.mounted++
212 tracker.listeners.add(check)
213 tracker.prefetches.forEach((_, query) => check(query))
214β
215 return () => {
216 tracker.listeners.delete(check)
217 timers.forEach((timer) => clearTimeout(timer))
218 timers.clear()
219 tracker.mounted--
220 // Stop tracking once no `QueryStrictMode` uses the tracker. Checked in a microtask, because
221 // `React.StrictMode` runs the effect again right after this cleanup.
222 queueMicrotask(() => {
223 if (tracker.mounted === 0 && prefetchTrackers.get(cache) === tracker) {
224 tracker.unsubscribe()
225 prefetchTrackers.delete(cache)
226 }
227 })
228 }
229 }, [cache, isNested, isRestoring, unusedPrefetchTimeout])
230β
231 const value = React.useMemo(
232 () => ({ handleMissingPrefetch }),
233 [handleMissingPrefetch],
234 )
235 return (
236 <QueryStrictModeProvider value={value}>{children}</QueryStrictModeProvider>
237 )
238}
239β
240// The query states a `'missing-prefetch'` was reported for. A component can render more than once
241// before it starts the fetch, for example in `React.StrictMode`, but each state is only reported
242// once
243const reportedMissingPrefetches = new WeakSet<
244 Query<any, any, any, any>['state']
245>()
246β
247/**
248 * Inside a `QueryStrictMode`, marks a query read by a hook as used, and reports a
249 * `'missing-prefetch'` if the hook is about to start the initial fetch of the query. Does nothing
250 * in production.
251 * @param strictMode - The value of the nearest `QueryStrictMode`, if any.
252 * @param cache - The cache of the hook's `QueryClient`.
253 * @param queryHash - The hash of the query the hook reads.
254 * @param result - The optimistic result of the hook.
255 * @param suspense - Whether the hook suspends while the query is pending.
256 * @throws {unknown} Whatever `handleMissingPrefetch` throws.
257 */
258export const checkQueryStrictMode = (
259 strictMode: QueryStrictModeValue | null,
260 cache: QueryCache,
261 queryHash: string,
262 result: QueryObserverResult<any, any>,
263 suspense: boolean,
264) => {
265 const query = strictMode && cache.get(queryHash)
266 if (!query) {
267 return
268 }
269 prefetchTrackers.get(cache)?.used.add(query)
270 // A suspending hook starts the fetch during render. Otherwise, the optimistic result reports
271 // `'fetching'` when the hook starts the fetch on mount, or after its options change.
272 const startsInitialFetch = suspense
273 ? result.isPending
274 : result.fetchStatus === 'fetching' && query.state.data === undefined
275 // Check the query's own state: the fetch hasn't started yet if it's still `'idle'`. A query
276 // that errored is refetched after an error boundary reset, which isn't a missing prefetch.
277 if (
278 startsInitialFetch &&
279 query.state.fetchStatus === 'idle' &&
280 query.state.status !== 'error'
281 ) {
282 const event: QueryStrictModeMissingPrefetchEvent = {
283 type: 'missing-prefetch',
284 suspense,
285 message: suspense
286 ? `[${query.queryHash}]: A suspense query started its fetch during render. Prefetch it higher up (in a route loader, with usePrefetchQuery, or on the server) to avoid request waterfalls.`
287 : `[${query.queryHash}]: A query started its fetch after rendering. Prefetch it higher up (in a route loader, with usePrefetchQuery, or on the server) to start the fetch earlier.`,
288 query,
289 }
290 if (!reportedMissingPrefetches.has(query.state)) {
291 // A throw from `handleMissingPrefetch` happens before the hook starts its fetch. The state
292 // is only marked once it returns, so the query stays idle and throws again after an error
293 // boundary reset.
294 strictMode.handleMissingPrefetch(event)
295 reportedMissingPrefetches.add(query.state)
296 }
297 }
298}