refactor useShallow (#2701)

This commit is contained in:
Daishi Kato 2024-08-27 10:13:01 +09:00 committed by GitHub
parent d7345da7cf
commit 2cadf6511d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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
}
}