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

HydrationBoundary.tsx

169 lines5.8 KB

1import { hydrate } from '@tanstack/query-core'
2import { Fragment } from 'preact'
3import { useEffect, useMemo, useRef } from 'preact/hooks'
4​
5import { useQueryClient } from './QueryClientProvider'
6import type { ComponentChildren } from 'preact'
7import type {
8 DehydratedState,
9 HydrateOptions,
10 OmitKeyof,
11 QueryClient,
12} from '@tanstack/query-core'
13​
14/** The props accepted by `HydrationBoundary`. */
15export interface HydrationBoundaryProps {
16 /** The state to hydrate. */
17 state: DehydratedState | null | undefined
18 /** Optional. Note: unlike `hydrate`, `mutations` cannot be set here. */
19 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
20 defaultOptions?: OmitKeyof<
21 Exclude<HydrateOptions['defaultOptions'], undefined>,
22 'mutations'
23 >
24 }
25 /**
26 * The components to render β€” always rendered unconditionally, not gated on
27 * hydration. New queries are hydrated into the cache during render; for
28 * queries that already exist in the cache, only newer dehydrated data is
29 * hydrated, and that happens in an effect after commit, so `children` may
30 * render briefly before it lands.
31 */
32 children?: ComponentChildren
33 /**
34 * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
35 * context will be used.
36 */
37 queryClient?: QueryClient
39​
40/**
41 * `HydrationBoundary` adds a previously dehydrated state into the `queryClient`
42 * that would be returned by `useQueryClient()`. If the client already contains
43 * data, the new queries will be intelligently merged based on update
44 * timestamp.
45 *
46 * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
47 *
48 * @example
49 * ;```tsx
50 * import { HydrationBoundary } from '@tanstack/preact-query'
51 *
52 * function App() {
53 * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
54 * }
55 * ```
56 *
57 * @example
58 * Server-side prefetch handed off to the client via `dehydrate`:
59 * ```tsx
60 * import { HydrationBoundary, dehydrate, noop } from '@tanstack/preact-query'
61 *
62 * async function ServerComponent() {
63 * const queryClient = getQueryClient()
64 *
65 * await queryClient
66 * .query({
67 * queryKey: ['posts'],
68 * queryFn: fetchPosts,
69 * })
70 * .catch(noop)
71 *
72 * return (
73 * <HydrationBoundary state={dehydrate(queryClient)}>
74 * <Posts />
75 * </HydrationBoundary>
76 * )
77 * }
78 * ```
79 *
80 * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an
81 * optional custom `queryClient`, and the `children` to render.
82 * @returns The provided `children`, rendered unconditionally. New queries in
83 * `state` are hydrated into the cache during render; for queries already in
84 * the cache, only newer dehydrated data is hydrated, in an effect after
85 * commit.
86 */
87export const HydrationBoundary = ({
88 children,
89 options = {},
90 state,
91 queryClient,
92}: HydrationBoundaryProps) => {
93 const client = useQueryClient(queryClient)
94​
95 const optionsRef = useRef(options)
96 useEffect(() => {
97 optionsRef.current = options
98 })
99​
100 // This useMemo is for performance reasons only, everything inside it must
101 // be safe to run in every render and code here should be read as "in render".
102 //
103 // This code needs to happen during the render phase, because after initial
104 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
105 // during a transition, we want to hydrate as much as is safe in render so
106 // we can prerender as much as possible.
107 //
108 // For any queries that already exist in the cache, we want to hold back on
109 // hydrating until _after_ the render phase. The reason for this is that during
110 // transitions, we don't want the existing queries and observers to update to
111 // the new data on the current page, only _after_ the transition is committed.
112 // If the transition is aborted, we will have hydrated any _new_ queries, but
113 // we throw away the fresh data for any existing ones to avoid unexpectedly
114 // updating the UI.
115 const hydrationQueue: DehydratedState['queries'] | undefined = 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 > 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 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 useEffect(() => {
163 if (hydrationQueue) {
164 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
165 }
166 }, [client, hydrationQueue])
167​
168 return <Fragment>{children}</Fragment>