File tree 3 files changed +11
-2
lines changed 3 files changed +11
-2
lines changed Original file line number Diff line number Diff line change @@ -18,6 +18,8 @@ export const prefetch = async (queries: (Query | unknown)[]) => {
18
18
. getQueriesData ( [ ] )
19
19
. map ( ( item ) => JSON . stringify ( item [ 0 ] ) )
20
20
21
+ /* Set the prefetched keys so we can check them after first
22
+ * render to make sure we are not prefetching anything unnecessarily */
21
23
queryClient . setQueryData ( [ "prefetchedKeys" ] , prefetchedKeys )
22
24
23
25
return dehydrate ( queryClient )
Original file line number Diff line number Diff line change @@ -25,10 +25,12 @@ export const useQuery = <
25
25
) : UseQueryResult < TData , TError > => {
26
26
const queryClient = useQueryClient ( )
27
27
28
- const cached = queryClient . getQueryState ( options . queryKey ! )
29
-
28
+ /* This flag is set to true when we get the window load event */
30
29
const initialLoaded = queryClient . getQueryData ( [ "initialRenderComplete" ] )
31
30
31
+ /* Check if the item is in the cache (implying prefetched, until initialLoaded) */
32
+ const cached = queryClient . getQueryState ( options . queryKey ! )
33
+
32
34
if ( ! initialLoaded ) {
33
35
if ( ! cached ) {
34
36
console . warn (
@@ -42,6 +44,7 @@ export const useQuery = <
42
44
43
45
const key = JSON . stringify ( options . queryKey )
44
46
if ( ! initialQueries . includes ( key ) ) {
47
+ /* Track the queries made during initial render so we can compare to the prefetched list */
45
48
queryClient . setQueryData ( [ "initialKeys" ] , [ ...initialQueries , key ] )
46
49
}
47
50
}
Original file line number Diff line number Diff line change @@ -7,19 +7,23 @@ export const useQueryCacheWarning = (queryClient: QueryClient) => {
7
7
queryClient . setQueryData ( [ "initialRenderComplete" ] , true )
8
8
window . removeEventListener ( "load" , onLoad )
9
9
10
+ /* These are the known keys set while prefetching on the server before dehydrating (serializing) for the client */
10
11
const prefetchedKeys = queryClient . getQueryData < string [ ] > ( [
11
12
"prefetchedKeys" ,
12
13
] )
13
14
15
+ /* These are the cache entries we set ourselves that are not queries, so we ignore below */
14
16
const nonQueryKeys = new Set ( [
15
17
'["prefetchedKeys"]' ,
16
18
'["initialRenderComplete"]' ,
17
19
] )
18
20
21
+ /* These are set as the components request useQuery() during initial render */
19
22
const initialKeys = new Set (
20
23
queryClient . getQueryData < string [ ] > ( [ "initialKeys" ] ) ,
21
24
)
22
25
26
+ /* We can find the keys prefetched but not used by any component during initial render */
23
27
const superfluousKeys = prefetchedKeys ?. filter (
24
28
( key ) => ! nonQueryKeys . has ( key ) && ! initialKeys . has ( key ) ,
25
29
)
You can’t perform that action at this time.
0 commit comments