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

HydrationBoundary.tsx

170 lines5.8 KB

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
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 * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom
50 * `queryClient`, and the `children` to render.
51 * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
52 * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
53 * after commit.
54 * @example
55 * ```tsx
56 * import { HydrationBoundary } from '@tanstack/react-query'
57 *
58 * function App() {
59 * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
60 * }
61 * ```
62 * @example
63 * Server-side prefetch handed off to the client via `dehydrate`:
64 * ```tsx
65 * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
66 *
67 * async function ServerComponent() {
68 * const queryClient = getQueryClient()
69 *
70 * await queryClient
71 * .query({
72 * queryKey: ['posts'],
73 * queryFn: fetchPosts,
74 * })
75 * .catch(noop)
76 *
77 * return (
78 * <HydrationBoundary state={dehydrate(queryClient)}>
79 * <Posts />
80 * </HydrationBoundary>
81 * )
82 * }
83 * ```
84 */
85export const HydrationBoundary = ({
86 children,
87 options = {},
88 state,
89 queryClient,
90}: HydrationBoundaryProps) => {
91 const client = useQueryClient(queryClient)
92​
93 const optionsRef = React.useRef(options)
94 React.useEffect(() => {
95 optionsRef.current = options
96 })
97​
98 // This useMemo is for performance reasons only, everything inside it must
99 // be safe to run in every render and code here should be read as "in render".
100 //
101 // This code needs to happen during the render phase, because after initial
102 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
103 // during a transition, we want to hydrate as much as is safe in render so
104 // we can prerender as much as possible.
105 //
106 // For any queries that already exist in the cache, we want to hold back on
107 // hydrating until _after_ the render phase. The reason for this is that during
108 // transitions, we don't want the existing queries and observers to update to
109 // the new data on the current page, only _after_ the transition is committed.
110 // If the transition is aborted, we will have hydrated any _new_ queries, but
111 // we throw away the fresh data for any existing ones to avoid unexpectedly
112 // updating the UI.
113 const hydrationQueue: DehydratedState['queries'] | undefined =
114 React.useMemo(() => {
115 if (state) {
116 if (typeof state !== 'object') {
117 return
118 }
119​
120 const queryCache = client.getQueryCache()
121 // State is supplied from the outside and we might as well fail
122 // gracefully if it has the wrong shape, so while we type `queries`
123 // as required, we still provide a fallback.
124 // oxlint-disable-next-line typescript/no-unnecessary-condition
125 const queries = state.queries || []
126​
127 const newQueries: DehydratedState['queries'] = []
128 const existingQueries: DehydratedState['queries'] = []
129 for (const dehydratedQuery of queries) {
130 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
131​
132 if (!existingQuery) {
133 newQueries.push(dehydratedQuery)
134 } else {
135 const hydrationIsNewer =
136 dehydratedQuery.state.dataUpdatedAt >
137 existingQuery.state.dataUpdatedAt ||
138 (dehydratedQuery.promise &&
139 existingQuery.state.status !== 'pending' &&
140 existingQuery.state.fetchStatus !== 'fetching' &&
141 dehydratedQuery.dehydratedAt >
142 existingQuery.state.dataUpdatedAt)
143​
144 if (hydrationIsNewer) {
145 existingQueries.push(dehydratedQuery)
146 }
147 }
148 }
149​
150 if (newQueries.length > 0) {
151 // It's actually fine to call this with queries/state that already exists
152 // in the cache, or is older. hydrate() is idempotent for queries.
153 // oxlint-disable-next-line react-hooks-js/refs
154 hydrate(client, { queries: newQueries }, optionsRef.current)
155 }
156 if (existingQueries.length > 0) {
157 return existingQueries
158 }
159 }
160 return undefined
161 }, [client, state])
162​
163 React.useEffect(() => {
164 if (hydrationQueue) {
165 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
166 }
167 }, [client, hydrationQueue])
168​
169 return children as React.ReactElement