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]: do not depend on use-sync-external-store #2301

Merged
merged 2 commits into from
Jan 20, 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
34 changes: 23 additions & 11 deletions src/react.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
// import { useDebugValue } from 'react'
// import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'
// Those don't work in ESM, because React libs are CJS only.
// import { useDebugValue, useSyncExternalStore } from 'react'
// That doesn't work in ESM, because React libs are CJS only.
// See: https://github.com/pmndrs/valtio/issues/452
// The following is a workaround until ESM is supported.
// eslint-disable-next-line import/extensions
import ReactExports from 'react'
// eslint-disable-next-line import/extensions
import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector'
import { createStore } from './vanilla.ts'
import type {
Mutate,
Expand All @@ -15,15 +12,31 @@ import type {
StoreMutatorIdentifier,
} from './vanilla.ts'

const { useDebugValue } = ReactExports
const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports
const { useDebugValue, useMemo, useSyncExternalStore } = ReactExports

type ExtractState<S> = S extends { getState: () => infer T } ? T : never

type ReadonlyStoreApi<T> = Pick<StoreApi<T>, 'getState' | 'subscribe'>

const identity = <T>(arg: T): T => arg

const useMemoSelector = <TState, StateSlice>(
getState: () => TState,
selector: (state: TState) => StateSlice,
) =>
useMemo(() => {
let lastSlice: StateSlice
let lastState: TState
return () => {
const state = getState()
if (!Object.is(lastState, state)) {
lastSlice = selector(state)
lastState = state
}
return lastSlice
}
}, [getState, selector])

export function useStore<S extends StoreApi<unknown>>(api: S): ExtractState<S>

export function useStore<S extends StoreApi<unknown>, U>(
Expand All @@ -35,11 +48,10 @@ export function useStore<TState, StateSlice>(
api: StoreApi<TState>,
selector: (state: TState) => StateSlice = identity as any,
) {
const slice = useSyncExternalStoreWithSelector(
const slice = useSyncExternalStore(
api.subscribe,
api.getState,
api.getInitialState,
selector,
useMemoSelector(api.getState, selector),
useMemoSelector(api.getInitialState, selector),
)
useDebugValue(slice)
return slice
Expand Down
Loading