Open History to see the last commit
1import React from 'react'
2β
3import { QueryClient } from '../core'
4β
5declare global {
6 interface Window {
7 ReactQueryClientContext?: React.Context<QueryClient | undefined>
8 }
9}
10β
11const defaultContext = React.createContext<QueryClient | undefined>(undefined)
12const QueryClientSharingContext = React.createContext<boolean>(false)
13β
14// if contextSharing is on, we share the first and at least one
15// instance of the context across the window
16// to ensure that if React Query is used across
17// different bundles or microfrontends they will
18// all use the same **instance** of context, regardless
19// of module scoping.
20function getQueryClientContext(contextSharing: boolean) {
21 if (contextSharing && typeof window !== 'undefined') {
22 if (!window.ReactQueryClientContext) {
23 window.ReactQueryClientContext = defaultContext
24 }
25β
26 return window.ReactQueryClientContext
27 }
28β
29 return defaultContext
30}
31β
32export const useQueryClient = () => {
33 const queryClient = React.useContext(
34 getQueryClientContext(React.useContext(QueryClientSharingContext))
35 )
36β
37 if (!queryClient) {
38 throw new Error('No QueryClient set, use QueryClientProvider to set one')
39 }
40β
41 return queryClient
42}
43β
44export interface QueryClientProviderProps {
45 client: QueryClient
46 contextSharing?: boolean
47 children?: React.ReactNode
48}
49β
50export const QueryClientProvider = ({
51 client,
52 contextSharing = false,
53 children,
54}: QueryClientProviderProps): JSX.Element => {
55 React.useEffect(() => {
56 client.mount()
57 return () => {
58 client.unmount()
59 }
60 }, [client])
61β
62 const Context = getQueryClientContext(contextSharing)
63β
64 return (
65 <QueryClientSharingContext.Provider value={contextSharing}>
66 <Context.Provider value={client}>{children}</Context.Provider>
67 </QueryClientSharingContext.Provider>
68 )
69}