Open History to see the last commit
1'use client'
2β
3import {
4 defaultShouldDehydrateQuery,
5 dehydrate,
6 environmentManager,
7 hydrate,
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 *
25 * - Dehydrating the query client on the server.
26 * - Hydrating the query client in the browser.
27 *
28 * @param props - The `children` to render, an optional custom `queryClient`,
29 * the `nonce` for the inline script, the hydrate and dehydrate `options`, and
30 * the data `transformer`.
31 * @returns The `children`, wrapped in the hydration stream provider.
32 */
33export function ReactQueryStreamedHydration(props: {
34 children: React.ReactNode
35 queryClient?: QueryClient
36 nonce?: string
37 options?: {
38 hydrate?: HydrateOptions
39 dehydrate?: DehydrateOptions
40 }
41 transformer?: HydrationStreamProviderProps<DehydratedState>['transformer']
42}) {
43 const queryClient = useQueryClient(props.queryClient)
44β
45 /** We need to track which queries were added/updated during the render */
46 const [trackedKeys] = React.useState(() => new Set<string>())
47β
48 // <server only>
49 if (environmentManager.isServer()) {
50 // Do we need to care about unsubscribing? I don't think so to be honest
51 queryClient.getQueryCache().subscribe((event) => {
52 switch (event.type) {
53 case 'added':
54 case 'updated':
55 // console.log('tracking', event.query.queryHash, 'b/c of a', event.type)
56 trackedKeys.add(event.query.queryHash)
57 }
58 })
59 }
60 // </server only>
61β
62 return (
63 <stream.Provider
64 // Happens on server:
65 onFlush={() => {
66 /**
67 * Dehydrated state of the client where we only include the queries that
68 * were added/updated since the last flush
69 */
70 const shouldDehydrate =
71 props.options?.dehydrate?.shouldDehydrateQuery ??
72 defaultShouldDehydrateQuery
73β
74 const dehydratedState = dehydrate(queryClient, {
75 ...props.options?.dehydrate,
76 shouldDehydrateQuery(query) {
77 return trackedKeys.has(query.queryHash) && shouldDehydrate(query)
78 },
79 })
80 trackedKeys.clear()
81β
82 if (!dehydratedState.queries.length) {
83 return []
84 }
85β
86 return [dehydratedState]
87 }}
88 // Happens in browser:
89 onEntries={(entries) => {
90 for (const hydratedState of entries) {
91 hydrate(queryClient, hydratedState, props.options?.hydrate)
92 }
93 }}
94 // Handle BigInts etc using superjson
95 transformer={props.transformer}
96 nonce={props.nonce}
97 >
98 {props.children}
99 </stream.Provider>
100 )
101}