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

ReactQueryCacheProvider.tsx

47 lines1.1 KB

1import React from 'react'
2​
3import {
4 QueryCache,
5 queryCache as defaultQueryCache,
6 queryCaches,
7} from '../core'
8​
9const queryCacheContext = React.createContext(defaultQueryCache)
10​
11export const useQueryCache = () => React.useContext(queryCacheContext)
12​
13export interface ReactQueryCacheProviderProps {
14 queryCache?: QueryCache
16​
17export const ReactQueryCacheProvider: React.FC<ReactQueryCacheProviderProps> = ({
18 queryCache,
19 children,
20}) => {
21 const resolvedQueryCache = React.useMemo(
22 () => queryCache || new QueryCache(),
23 [queryCache]
24 )
25​
26 React.useEffect(() => {
27 queryCaches.push(resolvedQueryCache)
28​
29 return () => {
30 // remove the cache from the active list
31 const i = queryCaches.indexOf(resolvedQueryCache)
32 if (i > -1) {
33 queryCaches.splice(i, 1)
34 }
35 // if the resolvedQueryCache was created by us, we need to tear it down
36 if (queryCache == null) {
37 resolvedQueryCache.clear({ notify: false })
38 }
39 }
40 }, [resolvedQueryCache, queryCache])
41​
42 return (
43 <queryCacheContext.Provider value={resolvedQueryCache}>
44 {children}
45 </queryCacheContext.Provider>
46 )