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

HydrationBoundary.tsx

168 lines5.6 KB

1import { hydrate } from '@tanstack/query-core'
2import type {
3 DehydratedState,
4 HydrateOptions,
5 OmitKeyof,
6 QueryClient,
7} from '@tanstack/query-core'
8import { Fragment } from 'preact'
9import type { ComponentChildren } from 'preact'
10import { useEffect, useMemo, useRef } from 'preact/hooks'
11​
12import { useQueryClient } from './QueryClientProvider'
13​
14/**
15 * The props accepted by `HydrationBoundary`.
16 */
17export interface HydrationBoundaryProps {
18 /**
19 * The state to hydrate.
20 */
21 state: DehydratedState | null | undefined
22 /**
23 * Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
24 */
25 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
26 defaultOptions?: OmitKeyof<
27 Exclude<HydrateOptions['defaultOptions'], undefined>,
28 'mutations'
29 >
30 }
31 /**
32 * The components to render β€” always rendered unconditionally, not gated on hydration. New queries are
33 * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
34 * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
35 * lands.
36 */
37 children?: ComponentChildren
38 /**
39 * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
40 */
41 queryClient?: QueryClient
43​
44/**
45 * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
46 * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
47 * update timestamp.
48 *
49 * Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
50 *
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 *
55 * @example
56 * ```tsx
57 * import { HydrationBoundary } from '@tanstack/preact-query'
58 *
59 * function App() {
60 * return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
61 * }
62 * ```
63 *
64 * @example
65 * Server-side prefetch handed off to the client via `dehydrate`:
66 * ```tsx
67 * import { HydrationBoundary, dehydrate, noop } from '@tanstack/preact-query'
68 *
69 * async function ServerComponent() {
70 * const queryClient = getQueryClient()
71 *
72 * await queryClient
73 * .query({
74 * queryKey: ['posts'],
75 * queryFn: fetchPosts,
76 * })
77 * .catch(noop)
78 *
79 * return (
80 * <HydrationBoundary state={dehydrate(queryClient)}>
81 * <Posts />
82 * </HydrationBoundary>
83 * )
84 * }
85 * ```
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 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 > 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 hydrate(client, { queries: newQueries }, optionsRef.current)
153 }
154 if (existingQueries.length > 0) {
155 return existingQueries
156 }
157 }
158 return undefined
159 }, [client, state])
160​
161 useEffect(() => {
162 if (hydrationQueue) {
163 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
164 }
165 }, [client, hydrationQueue])
166​
167 return <Fragment>{children}</Fragment>