Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

ReactQueryStreamedHydration.tsx

96 lines2.6 KB

1'use client'
2​
3import {
4 defaultShouldDehydrateQuery,
5 dehydrate,
6 hydrate,
7 isServer,
8 useQueryClient,
9} from '@tanstack/react-query'
10import * as React from 'react'
11import { createHydrationStreamProvider } from './HydrationStreamProvider'
12import type { HydrationStreamProviderProps } from './HydrationStreamProvider'
13import type {
14 DehydrateOptions,
15 DehydratedState,
16 HydrateOptions,
17 QueryClient,
18} from '@tanstack/react-query'
19​
20const stream = createHydrationStreamProvider<DehydratedState>()
21​
22/**
23 * This component is responsible for:
24 * - hydrating the query client on the server
25 * - dehydrating the query client on the server
26 */
27export function ReactQueryStreamedHydration(props: {
28 children: React.ReactNode
29 queryClient?: QueryClient
30 nonce?: string
31 options?: {
32 hydrate?: HydrateOptions
33 dehydrate?: DehydrateOptions
34 }
35 transformer?: HydrationStreamProviderProps<DehydratedState>['transformer']
36}) {
37 const queryClient = useQueryClient(props.queryClient)
38​
39 /**
40 * We need to track which queries were added/updated during the render
41 */
42 const [trackedKeys] = React.useState(() => new Set<string>())
43​
44 // <server only>
45 if (isServer) {
46 // Do we need to care about unsubscribing? I don't think so to be honest
47 queryClient.getQueryCache().subscribe((event) => {
48 switch (event.type) {
49 case 'added':
50 case 'updated':
51 // console.log('tracking', event.query.queryHash, 'b/c of a', event.type)
52 trackedKeys.add(event.query.queryHash)
53 }
54 })
55 }
56 // </server only>
57​
58 return (
59 <stream.Provider
60 // Happens on server:
61 onFlush={() => {
62 /**
63 * Dehydrated state of the client where we only include the queries that were added/updated since the last flush
64 */
65 const shouldDehydrate =
66 props.options?.dehydrate?.shouldDehydrateQuery ??
67 defaultShouldDehydrateQuery
68​
69 const dehydratedState = dehydrate(queryClient, {
70 ...props.options?.dehydrate,
71 shouldDehydrateQuery(query) {
72 return trackedKeys.has(query.queryHash) && shouldDehydrate(query)
73 },
74 })
75 trackedKeys.clear()
76​
77 if (!dehydratedState.queries.length) {
78 return []
79 }
80​
81 return [dehydratedState]
82 }}
83 // Happens in browser:
84 onEntries={(entries) => {
85 for (const hydratedState of entries) {
86 hydrate(queryClient, hydratedState, props.options?.hydrate)
87 }
88 }}
89 // Handle BigInts etc using superjson
90 transformer={props.transformer}
91 nonce={props.nonce}
92 >
93 {props.children}
94 </stream.Provider>
95 )