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

[v5]: refactor useMemoSelector #2302

Merged
merged 4 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
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
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')
})
Loading