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

ReactQueryStreamedHydration.tsx

99 lines2.9 KB

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