Skip to content

Commit

Permalink
[v5]: refactor useMemoSelector (#2302)
Browse files Browse the repository at this point in the history
* [v5]: refactor useMemoSelector

* add a test

* Revert "[v5]: refactor useMemoSelector"

This reverts commit b3c8b15.

* Revert "Revert "[v5]: refactor useMemoSelector""

This reverts commit 3c47301.
  • Loading branch information
dai-shi authored Jan 21, 2024
1 parent 43986a3 commit f8a4d58
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
10 changes: 4 additions & 6 deletions src/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,13 @@ const useMemoSelector = <TState, StateSlice>(
selector: (state: TState) => StateSlice,
) =>
useMemo(() => {
let lastSlice: StateSlice
let lastState: TState
let prev: readonly [TState, StateSlice] | undefined
return () => {
const state = getState()
if (!Object.is(lastState, state)) {
lastSlice = selector(state)
lastState = state
if (!prev || !Object.is(prev[0], state)) {
prev = [state, selector(state)]
}
return lastSlice
return prev[1]
}
}, [getState, selector])

Expand Down
2 changes: 1 addition & 1 deletion src/react/shallow.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// import { useDebugValue } from 'react'
// import { useRef } from 'react'
// That doesnt work in ESM, because React libs are CJS only.
// The following is a workaround until ESM is supported.
// eslint-disable-next-line import/extensions
Expand Down
17 changes: 17 additions & 0 deletions tests/basic.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -680,3 +680,20 @@ it('works with non-object state', async () => {
fireEvent.click(getByText('button'))
await findByText('count: 2')
})

it('works with "undefined" state', async () => {
const useUndefined = create(() => undefined)

const Component = () => {
const str = useUndefined((v) => v || 'undefined')
return <div>str: {str}</div>
}

const { findByText } = render(
<StrictMode>
<Component />
</StrictMode>,
)

await findByText('str: undefined')
})

0 comments on commit f8a4d58

Please sign in to comment.