Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor useShallow #2701

Merged
merged 2 commits into from
Aug 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}