Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import { hydrate } from '@tanstack/query-core'
5import { useQueryClient } from './QueryClientProvider'
6import type {
7 DehydratedState,
8 HydrateOptions,
9 OmitKeyof,
10 QueryClient,
11} from '@tanstack/query-core'
12β
13/**
14 * The props accepted by `HydrationBoundary`.
15 */
16export interface HydrationBoundaryProps {
17 /**
18 * The state to hydrate.
19 */
20 state: DehydratedState | null | undefined
21 /**
22 * Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
23 */
24 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
25 defaultOptions?: OmitKeyof<
26 Exclude<HydrateOptions['defaultOptions'], undefined>,
27 'mutations'
28 >
29 }
30 /**
31 * The components to render β always rendered unconditionally, not gated on hydration. New queries are
32 * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
33 * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
34 * lands.
35 */
36 children?: React.ReactNode
37 /**
38 * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
39 */
40 queryClient?: QueryClient
41}
42β
43/**
44 * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
45 * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
46 * update timestamp.
47 *
48 * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
49 *
50 * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
51 * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
52 * after commit.
53 *
54 * @example
55 * ```tsx
56 * import { HydrationBoundary } from '@tanstack/react-query'
57 *
58 * function App() {
59 * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
60 * }
61 * ```
62 *
63 * @example
64 * Server-side prefetch handed off to the client via `dehydrate`:
65 * ```tsx
66 * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
67 *
68 * async function ServerComponent() {
69 * const queryClient = getQueryClient()
70 *
71 * await queryClient
72 * .query({
73 * queryKey: ['posts'],
74 * queryFn: fetchPosts,
75 * })
76 * .catch(noop)
77 *
78 * return (
79 * <HydrationBoundary state={dehydrate(queryClient)}>
80 * <Posts />
81 * </HydrationBoundary>
82 * )
83 * }
84 * ```
85 */
86export const HydrationBoundary = ({
87 children,
88 options = {},
89 state,
90 queryClient,
91}: HydrationBoundaryProps) => {
92 const client = useQueryClient(queryClient)
93β
94 const optionsRef = React.useRef(options)
95 React.useEffect(() => {
96 optionsRef.current = options
97 })
98β
99 // This useMemo is for performance reasons only, everything inside it must
100 // be safe to run in every render and code here should be read as "in render".
101 //
102 // This code needs to happen during the render phase, because after initial
103 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
104 // during a transition, we want to hydrate as much as is safe in render so
105 // we can prerender as much as possible.
106 //
107 // For any queries that already exist in the cache, we want to hold back on
108 // hydrating until _after_ the render phase. The reason for this is that during
109 // transitions, we don't want the existing queries and observers to update to
110 // the new data on the current page, only _after_ the transition is committed.
111 // If the transition is aborted, we will have hydrated any _new_ queries, but
112 // we throw away the fresh data for any existing ones to avoid unexpectedly
113 // updating the UI.
114 const hydrationQueue: DehydratedState['queries'] | undefined =
115 React.useMemo(() => {
116 if (state) {
117 if (typeof state !== 'object') {
118 return
119 }
120β
121 const queryCache = client.getQueryCache()
122 // State is supplied from the outside and we might as well fail
123 // gracefully if it has the wrong shape, so while we type `queries`
124 // as required, we still provide a fallback.
125 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
126 const queries = state.queries || []
127β
128 const newQueries: DehydratedState['queries'] = []
129 const existingQueries: DehydratedState['queries'] = []
130 for (const dehydratedQuery of queries) {
131 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
132β
133 if (!existingQuery) {
134 newQueries.push(dehydratedQuery)
135 } else {
136 const hydrationIsNewer =
137 dehydratedQuery.state.dataUpdatedAt >
138 existingQuery.state.dataUpdatedAt ||
139 (dehydratedQuery.promise &&
140 existingQuery.state.status !== 'pending' &&
141 existingQuery.state.fetchStatus !== 'fetching' &&
142 dehydratedQuery.dehydratedAt >
143 existingQuery.state.dataUpdatedAt)
144β
145 if (hydrationIsNewer) {
146 existingQueries.push(dehydratedQuery)
147 }
148 }
149 }
150β
151 if (newQueries.length > 0) {
152 // It's actually fine to call this with queries/state that already exists
153 // in the cache, or is older. hydrate() is idempotent for queries.
154 // eslint-disable-next-line react-hooks/refs
155 hydrate(client, { queries: newQueries }, optionsRef.current)
156 }
157 if (existingQueries.length > 0) {
158 return existingQueries
159 }
160 }
161 return undefined
162 }, [client, state])
163β
164 React.useEffect(() => {
165 if (hydrationQueue) {
166 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
167 }
168 }, [client, hydrationQueue])
169β
170 return children as React.ReactElement
171}