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

HydrationBoundary.tsx

109 lines3.8 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​
14export interface HydrationBoundaryProps {
15 state: DehydratedState | null | undefined
16 options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
17 defaultOptions?: OmitKeyof<
18 Exclude<HydrateOptions['defaultOptions'], undefined>,
19 'mutations'
20 >
21 }
22 children?: ComponentChildren
23 queryClient?: QueryClient
25​
26export const HydrationBoundary = ({
27 children,
28 options = {},
29 state,
30 queryClient,
31}: HydrationBoundaryProps) => {
32 const client = useQueryClient(queryClient)
33​
34 const optionsRef = useRef(options)
35 useEffect(() => {
36 optionsRef.current = options
37 })
38​
39 // This useMemo is for performance reasons only, everything inside it must
40 // be safe to run in every render and code here should be read as "in render".
41 //
42 // This code needs to happen during the render phase, because after initial
43 // SSR, hydration needs to happen _before_ children render. Also, if hydrating
44 // during a transition, we want to hydrate as much as is safe in render so
45 // we can prerender as much as possible.
46 //
47 // For any queries that already exist in the cache, we want to hold back on
48 // hydrating until _after_ the render phase. The reason for this is that during
49 // transitions, we don't want the existing queries and observers to update to
50 // the new data on the current page, only _after_ the transition is committed.
51 // If the transition is aborted, we will have hydrated any _new_ queries, but
52 // we throw away the fresh data for any existing ones to avoid unexpectedly
53 // updating the UI.
54 const hydrationQueue: DehydratedState['queries'] | undefined = useMemo(() => {
55 if (state) {
56 if (typeof state !== 'object') {
57 return
58 }
59​
60 const queryCache = client.getQueryCache()
61 // State is supplied from the outside and we might as well fail
62 // gracefully if it has the wrong shape, so while we type `queries`
63 // as required, we still provide a fallback.
64 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
65 const queries = state.queries || []
66​
67 const newQueries: DehydratedState['queries'] = []
68 const existingQueries: DehydratedState['queries'] = []
69 for (const dehydratedQuery of queries) {
70 const existingQuery = queryCache.get(dehydratedQuery.queryHash)
71​
72 if (!existingQuery) {
73 newQueries.push(dehydratedQuery)
74 } else {
75 const hydrationIsNewer =
76 dehydratedQuery.state.dataUpdatedAt >
77 existingQuery.state.dataUpdatedAt ||
78 (dehydratedQuery.promise &&
79 existingQuery.state.status !== 'pending' &&
80 existingQuery.state.fetchStatus !== 'fetching' &&
81 dehydratedQuery.dehydratedAt !== undefined &&
82 dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt)
83​
84 if (hydrationIsNewer) {
85 existingQueries.push(dehydratedQuery)
86 }
87 }
88 }
89​
90 if (newQueries.length > 0) {
91 // It's actually fine to call this with queries/state that already exists
92 // in the cache, or is older. hydrate() is idempotent for queries.
93 hydrate(client, { queries: newQueries }, optionsRef.current)
94 }
95 if (existingQueries.length > 0) {
96 return existingQueries
97 }
98 }
99 return undefined
100 }, [client, state])
101​
102 useEffect(() => {
103 if (hydrationQueue) {
104 hydrate(client, { queries: hydrationQueue }, optionsRef.current)
105 }
106 }, [client, hydrationQueue])
107​
108 return <Fragment>{children}</Fragment>