diff --git a/src/lib/middleware.ts b/src/lib/middleware.ts index bf554e3..428d1b8 100644 --- a/src/lib/middleware.ts +++ b/src/lib/middleware.ts @@ -272,7 +272,7 @@ export const converter = (historyInstance: History) => (set, get) => { set( state => { state.subscribers = 1 - state.unsubscribe = () => { + state.unsubscribe = (cb?: () => void) => { set(thisState => { // it's possible that the state namespace has been cleared by the provider if (!thisState[ns]) { @@ -282,6 +282,9 @@ export const converter = (historyInstance: History) => (set, get) => { if (thisState[ns].subscribers === 0) { // tslint:disable-next-line:no-delete delete thisState[ns] + if (cb) { + cb() + } } }, HistoryEventType.REGISTER) } diff --git a/src/lib/store.ts b/src/lib/store.ts index ea5110a..d020609 100644 --- a/src/lib/store.ts +++ b/src/lib/store.ts @@ -58,6 +58,8 @@ export const factoryParameters = ( ns: string = DEFAULT_NAMESPACE ) => { const flatConfig = flattenConfig(config) + // tslint:disable-next-line:no-let + let initialCache: { readonly query: object; readonly values: T } | null const useQuery = () => { const [useStore, api] = useContext(StoreContext) as [ UseStore>, @@ -91,6 +93,10 @@ export const factoryParameters = ( ) const initialRegisterState = useMemo(() => { + // in case this namespace has been initialized already, reuse the result. + if (initialCache) { + return initialCache + } // thisValues will be mutated by applyFlatConfigToState, that's why we init it with a copy of // the initial state. const thisValues = { ...defaultInitialValues } @@ -101,10 +107,11 @@ export const factoryParameters = ( thisValues, defaultInitialValues ) - return { + initialCache = { query, values: thisValues } + return initialCache }, []) const [currentState, setCurrentState] = useState({ @@ -139,8 +146,11 @@ export const factoryParameters = ( ) return () => { - unregister() unsubscribe() + unregister(() => { + // When all subscribers are removed, we also clear the cache + initialCache = null + }) } }, [])