Skip to content

Commit 7c9af65

Browse files
committed
add cache to injected slices
1 parent d624fa3 commit 7c9af65

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

packages/toolkit/src/createSlice.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,8 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
732732
>
733733
>()
734734

735+
const injectedStateCache = new WeakMap<(rootState: any) => State, State>()
736+
735737
let _reducer: ReducerWithInitialState<State>
736738

737739
function reducer(state: State | undefined, action: UnknownAction) {
@@ -757,7 +759,11 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
757759
let sliceState = state[reducerPath]
758760
if (typeof sliceState === 'undefined') {
759761
if (injected) {
760-
sliceState = getInitialState()
762+
sliceState = getOrInsertComputed(
763+
injectedStateCache,
764+
selectSlice,
765+
getInitialState,
766+
)
761767
} else if (process.env.NODE_ENV !== 'production') {
762768
throw new Error(
763769
'selectSlice returned undefined for an uninjected slice reducer',
@@ -766,6 +772,7 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
766772
}
767773
return sliceState
768774
}
775+
769776
function getSelectors(
770777
selectState: (rootState: any) => State = selectSelf,
771778
) {
@@ -783,7 +790,12 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
783790
map[name] = wrapSelector(
784791
selector,
785792
selectState,
786-
getInitialState,
793+
() =>
794+
getOrInsertComputed(
795+
injectedStateCache,
796+
selectState,
797+
getInitialState,
798+
),
787799
injected,
788800
)
789801
}

0 commit comments

Comments
 (0)