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

react.tsx

35 lines949 Bytes

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