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