Skip to content

Commit 2cadf65

Browse files
authored
refactor useShallow (#2701)
1 parent d7345da commit 2cadf65

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/react/shallow.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,17 @@ import { shallow } from '../vanilla/shallow.ts'
66

77
const { useRef } = ReactExports
88

9-
export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
10-
const prev = useRef<U>()
9+
const sliceCache = new WeakMap<object, unknown>()
1110

11+
export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
12+
const key = useRef({}).current
1213
return (state) => {
14+
const prev = sliceCache.get(key) as U | undefined
1315
const next = selector(state)
14-
return shallow(prev.current, next)
15-
? (prev.current as U)
16-
: // It might not work with React Compiler
17-
// eslint-disable-next-line react-compiler/react-compiler
18-
(prev.current = next)
16+
if (shallow(prev, next)) {
17+
return prev as U
18+
}
19+
sliceCache.set(key, next)
20+
return next
1921
}
2022
}

0 commit comments

Comments
 (0)