Skip to content

Commit

Permalink
fix(performance): added memoization for namespace init.
Browse files Browse the repository at this point in the history
  • Loading branch information
BowlingX committed Dec 5, 2019
1 parent 5051792 commit 5692db6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/lib/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]) {
Expand All @@ -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)
}
Expand Down
14 changes: 12 additions & 2 deletions src/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export const factoryParameters = <T = object>(
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<StoreState<T>>,
Expand Down Expand Up @@ -91,6 +93,10 @@ export const factoryParameters = <T = object>(
)

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 }
Expand All @@ -101,10 +107,11 @@ export const factoryParameters = <T = object>(
thisValues,
defaultInitialValues
)
return {
initialCache = {
query,
values: thisValues
}
return initialCache
}, [])

const [currentState, setCurrentState] = useState({
Expand Down Expand Up @@ -139,8 +146,11 @@ export const factoryParameters = <T = object>(
)

return () => {
unregister()
unsubscribe()
unregister(() => {
// When all subscribers are removed, we also clear the cache
initialCache = null
})
}
}, [])

Expand Down

0 comments on commit 5692db6

Please sign in to comment.