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

HydrationBoundary.tsx

113 lines3.7 KB

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