Open History to see the last commit
1import * as React from 'react'
2β
3import type { HydrateOptions } from '@tanstack/query-core'
4import { hydrate } from '@tanstack/query-core'
5import { useQueryClient } from './QueryClientProvider'
6import type { ContextOptions } from './types'
7β
8export function useHydrate(
9 state: unknown,
10 options: HydrateOptions & ContextOptions = {},
11) {
12 const queryClient = useQueryClient({ context: options.context })
13β
14 const optionsRef = React.useRef(options)
15 optionsRef.current = options
16β
17 // Running hydrate again with the same queries is safe,
18 // it wont overwrite or initialize existing queries,
19 // relying on useMemo here is only a performance optimization.
20 // hydrate can and should be run *during* render here for SSR to work properly
21 React.useMemo(() => {
22 if (state) {
23 hydrate(queryClient, state, optionsRef.current)
24 }
25 }, [queryClient, state])
26}
27β
28export interface HydrateProps {
29 state?: unknown
30 options?: HydrateOptions
31 children?: React.ReactNode
32}
33β
34export const Hydrate = ({ children, options, state }: HydrateProps) => {
35 useHydrate(state, options)
36 return children as React.ReactElement
37}