Files
SnowLuma/.pnpm-store/v11/files/9e/14eacb28ea6ad655d38665c9805cbcd67cf905eb633c1fb1c6d2b0d54ed53a28200491a94bc5a23e55d22ccfe2aa80ffb25ae6f6a97aba3c9bc32c6b0df76a
TanTan 2a69b23b47
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

45 lines
1.1 KiB
Plaintext

import { useCallback } from 'react'
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'
import type { AnyAtom } from '@tanstack/store'
type SyncExternalStoreSubscribe = Parameters<
typeof useSyncExternalStoreWithSelector
>[0]
function defaultCompare<T>(a: T, b: T) {
return a === b
}
export function useStore<TAtom extends AnyAtom | undefined, T>(
atom: TAtom,
selector: (
snapshot: TAtom extends { get: () => infer TSnapshot }
? TSnapshot
: undefined,
) => T,
compare: (a: T, b: T) => boolean = defaultCompare,
): T {
const subscribe: SyncExternalStoreSubscribe = useCallback(
(handleStoreChange) => {
if (!atom) {
return () => {}
}
const { unsubscribe } = atom.subscribe(handleStoreChange)
return unsubscribe
},
[atom],
)
const boundGetSnapshot = useCallback(() => atom?.get(), [atom])
const selectedSnapshot = useSyncExternalStoreWithSelector(
subscribe,
boundGetSnapshot,
boundGetSnapshot,
selector,
compare,
)
return selectedSnapshot
}