-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
10 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,12 @@ | ||
// import { useRef } from 'react' | ||
// That doesnt work in ESM, because React libs are CJS only. | ||
// The following is a workaround until ESM is supported. | ||
import ReactExports from 'react' | ||
import React from 'react' | ||
import { shallow } from '../vanilla/shallow.ts' | ||
|
||
const { useRef } = ReactExports | ||
|
||
const sliceCache = new WeakMap<object, unknown>() | ||
|
||
export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U { | ||
const key = useRef({}).current | ||
const prev = React.useRef<U>() | ||
return (state) => { | ||
const prev = sliceCache.get(key) as U | undefined | ||
const next = selector(state) | ||
if (shallow(prev, next)) { | ||
return prev as U | ||
} | ||
sliceCache.set(key, next) | ||
return next | ||
return shallow(prev.current, next) | ||
? (prev.current as U) | ||
: (prev.current = next) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters