mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
refactor useShallow (#2701)
This commit is contained in:
parent
d7345da7cf
commit
2cadf6511d
@ -6,15 +6,17 @@ import { shallow } from '../vanilla/shallow.ts'
|
||||
|
||||
const { useRef } = ReactExports
|
||||
|
||||
export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
|
||||
const prev = useRef<U>()
|
||||
const sliceCache = new WeakMap<object, unknown>()
|
||||
|
||||
export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
|
||||
const key = useRef({}).current
|
||||
return (state) => {
|
||||
const prev = sliceCache.get(key) as U | undefined
|
||||
const next = selector(state)
|
||||
return shallow(prev.current, next)
|
||||
? (prev.current as U)
|
||||
: // It might not work with React Compiler
|
||||
// eslint-disable-next-line react-compiler/react-compiler
|
||||
(prev.current = next)
|
||||
if (shallow(prev, next)) {
|
||||
return prev as U
|
||||
}
|
||||
sliceCache.set(key, next)
|
||||
return next
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user