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/** The props accepted by `HydrationBoundary`. */
14export interface HydrationBoundaryProps {
15 /** The state to hydrate. */
16 state: DehydratedState | null | undefined
17 /** Optional. Note: unlike `hydrate`, `mutations` cannot be set here. */
18 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
19 defaultOptions?: OmitKeyof<
20 Exclude<HydrateOptions['defaultOptions'], undefined>,
21 'mutations'
22 >
23 }
24 /**
25 * The components to render β always rendered unconditionally, not gated on
26 * hydration. New queries are hydrated into the cache during render; for
27 * queries that already exist in the cache, only newer dehydrated data is
28 * hydrated, and that happens in an effect after commit, so `children` may
29 * render briefly before it lands.
30 */
31 children?: React.ReactNode
32 /**
33 * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
34 * context will be used.
35 */
36 queryClient?: QueryClient
37}
38β
39/**
40 * `HydrationBoundary` adds a previously dehydrated state into the `queryClient`
41 * that would be returned by `useQueryClient()`. If the client already contains
42 * data, the new queries will be intelligently merged based on update
43 * timestamp.
44 *
45 * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
46 *
47 * @example
48 * ;```tsx
49 * import { HydrationBoundary } from '@tanstack/react-query'
50 *
51 * function App() {
52 * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
53 * }
54 * ```
55 *
56 * @example
57 * Server-side prefetch handed off to the client via `dehydrate`:
58 * ```tsx
59 * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
60 *
61 * async function ServerComponent() {
62 * const queryClient = getQueryClient()
63 *
64 * await queryClient
65 * .query({
66 * queryKey: ['posts'],
67 * queryFn: fetchPosts,
68 * })
69 * .catch(noop)
70 *
71 * return (
72 * <HydrationBoundary state={dehydrate(queryClient)}>
73 * <Posts />
74 * </HydrationBoundary>
75 * )
76 * }
77 * ```
78 *
79 * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an
80 * optional custom `queryClient`, and the `children` to render.
81 * @returns The provided `children`, rendered unconditionally. New queries in
82 * `state` are hydrated into the cache during render; for queries already in
83 * the cache, only newer dehydrated data is hydrated, in an effect after
84 * commit.
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 // oxlint-disable-next-line typescript/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 // oxlint-disable-next-line react-hooks-js/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}