Skip to content

Commit

Permalink
refactor useShallow (#2701)
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi authored Aug 27, 2024
1 parent d7345da commit 2cadf65
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/react/shallow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

0 comments on commit 2cadf65

Please sign in to comment.