From 01444415fc29f46a77f36693fac369dc1348ce40 Mon Sep 17 00:00:00 2001 From: daishi Date: Tue, 15 Oct 2024 20:03:59 +0900 Subject: [PATCH] fix(provider): make react compiler happy --- src/react/Provider.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/react/Provider.ts b/src/react/Provider.ts index a4c1345992..b743c0b18a 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 { FunctionComponentElement, 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, @@ -27,14 +35,11 @@ export const Provider = ({ children?: ReactNode store?: Store }): FunctionComponentElement<{ value: Store | undefined }> => { - const storeRef = useRef() - if (!store && !storeRef.current) { - storeRef.current = createStore() - } + const [key] = useState({}) return createElement( StoreContext.Provider, { - value: store || storeRef.current, + value: store || getStoreForProvider(key), }, children, )