Open History to see the last commit
1/* eslint-disable react-compiler/react-compiler */
2β
3'use client'
4import * as React from 'react'
5β
6import { hydrate } from '@tanstack/query-core'
7import { useQueryClient } from './QueryClientProvider'
8import type {
9 DehydratedState,
10 HydrateOptions,
11 OmitKeyof,
12 QueryClient,
13} from '@tanstack/query-core'
14β
15export interface HydrationBoundaryProps {
16 state?: unknown
17 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
18 defaultOptions?: OmitKeyof<
19 Exclude<HydrateOptions['defaultOptions'], undefined>,
20 'mutations'
21 >
22 }
23 children?: React.ReactNode
24 queryClient?: QueryClient
25}
26β
27const hasProperty = <TKey extends string>(
28 obj: unknown,
29 key: TKey,
30): obj is { [k in TKey]: unknown } => {
31 return typeof obj === 'object' && obj !== null && key in obj
32}
33β
34export const HydrationBoundary = ({
35 children,
36 options = {},
37 state,
38 queryClient,
39}: HydrationBoundaryProps) => {
40 const client = useQueryClient(queryClient)
41 const [hydrationQueue, setHydrationQueue] = React.useState<
42 DehydratedState['queries'] | undefined
43 >()
44β
45 const optionsRef = React.useRef(options)
46 optionsRef.current = options
47β
48 // This useMemo is for performance reasons only, everything inside it _must_
49 // be safe to run in every render and code here should be read as "in render".
50 //
51 // This code needs to happen during the render phase, because after initial
52 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
53 // during a transition, we want to hydrate as much as is safe in render so
54 // we can prerender as much as possible.
55 //
56 // For any queries that already exist in the cache, we want to hold back on
57 // hydrating until _after_ the render phase. The reason for this is that during
58 // transitions, we don't want the existing queries and observers to update to
59 // the new data on the current page, only _after_ the transition is committed.
60 // If the transition is aborted, we will have hydrated any _new_ queries, but
61 // we throw away the fresh data for any existing ones to avoid unexpectedly
62 // updating the UI.
63 React.useMemo(() => {
64 if (state) {
65 if (typeof state !== 'object') {
66 return
67 }
68β
69 const queryCache = client.getQueryCache()
70 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
71 const queries = (state as DehydratedState).queries || []
72β
73 const newQueries: DehydratedState['queries'] = []
74 const existingQueries: DehydratedState['queries'] = []
75 for (const dehydratedQuery of queries) {
76 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
77β
78 if (!existingQuery) {
79 newQueries.push(dehydratedQuery)
80 } else {
81 const hydrationIsNewer =
82 dehydratedQuery.state.dataUpdatedAt >
83 existingQuery.state.dataUpdatedAt || // RSC special serialized then-able chunks
84 (hasProperty(dehydratedQuery.promise, 'status') &&
85 hasProperty(existingQuery.promise, 'status') &&
86 dehydratedQuery.promise.status !== existingQuery.promise.status)
87β
88 const queryAlreadyQueued = hydrationQueue?.find(
89 (query) => query.queryHash === dehydratedQuery.queryHash,
90 )
91β
92 if (
93 hydrationIsNewer &&
94 (!queryAlreadyQueued ||
95 dehydratedQuery.state.dataUpdatedAt >
96 queryAlreadyQueued.state.dataUpdatedAt)
97 ) {
98 existingQueries.push(dehydratedQuery)
99 }
100 }
101 }
102β
103 if (newQueries.length > 0) {
104 // It's actually fine to call this with queries/state that already exists
105 // in the cache, or is older. hydrate() is idempotent for queries.
106 hydrate(client, { queries: newQueries }, optionsRef.current)
107 }
108 if (existingQueries.length > 0) {
109 setHydrationQueue((prev) =>
110 prev ? [...prev, ...existingQueries] : existingQueries,
111 )
112 }
113 }
114 }, [client, hydrationQueue, state])
115β
116 React.useEffect(() => {
117 if (hydrationQueue) {
118 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
119 setHydrationQueue(undefined)
120 }
121 }, [client, hydrationQueue])
122β
123 return children as React.ReactElement
124}