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

Hydrate.tsx

37 lines1.2 KB

1import React from 'react'
2​
3import { hydrate, HydrateOptions } from '../core'
4import { useQueryClient } from './QueryClientProvider'
5​
6const IsHydratingContext = React.createContext(false)
7​
8export const useIsHydrating = () => React.useContext(IsHydratingContext)
9export const IsHydratingProvider = IsHydratingContext.Provider
10​
11export function useHydrate(state: unknown, options: HydrateOptions = {}) {
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])
27​
28export interface HydrateProps {
29 state?: unknown
30 options?: HydrateOptions
31 children?: React.ReactNode
33​
34export const Hydrate = ({ children, options, state }: HydrateProps) => {
35 useHydrate(state, options)
36 return children as React.ReactElement