diff --git a/src/react/Provider.ts b/src/react/Provider.ts index f733c1186d..e563fe9611 100644 --- a/src/react/Provider.ts +++ b/src/react/Provider.ts @@ -1,4 +1,4 @@ -import { createContext, createElement, useContext, useRef } from 'react' +import { createContext, createElement, useContext, useState } from 'react' import type { FunctionComponent, ReactElement, ReactNode } from 'react' import { createStore, getDefaultStore } from '../vanilla.ts' @@ -18,8 +18,16 @@ export const useStore = (options?: Options): Store => { return options?.store || store || getDefaultStore() } -/* eslint-disable react-compiler/react-compiler */ -// TODO should we consider using useState instead of useRef? +const storeCache = new WeakMap() +const getStoreForProvider = (key: object) => { + let store = storeCache.get(key) + if (!store) { + store = createStore() + storeCache.set(key, store) + } + return store +} + export const Provider = ({ children, store, @@ -30,14 +38,11 @@ export const Provider = ({ { value: Store | undefined }, FunctionComponent<{ value: Store | undefined }> > => { - const storeRef = useRef(undefined) - if (!store && !storeRef.current) { - storeRef.current = createStore() - } + const [key] = useState({}) return createElement( StoreContext.Provider, { - value: store || storeRef.current, + value: store || getStoreForProvider(key), }, children, )