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}
48β
49export const QueryClientProvider: React.FC<QueryClientProviderProps> = ({
50 client,
51 contextSharing = false,
52 children,
53}) => {
54 React.useEffect(() => {
55 client.mount()
56 return () => {
57 client.unmount()
58 }
59 }, [client])
60β
61 const Context = getQueryClientContext(contextSharing)
62β
63 return (
64 <QueryClientSharingContext.Provider value={contextSharing}>
65 <Context.Provider value={client}>{children}</Context.Provider>
66 </QueryClientSharingContext.Provider>
67 )
68}