import { useState } from 'preact/hooks' import { createStore } from '@tanstack/store' // eslint-disable-next-line no-duplicate-imports import type { ReadonlyStore, Store, StoreActionMap, StoreActionsFactory, } from '@tanstack/store' type NonFunction = T extends (...args: Array) => any ? never : T /** * Creates a stable store instance for the lifetime of the component. * * Pass an initial value to create a writable store, or a getter function to * create a readonly derived store. This mirrors {@link createStore}, but only * creates the store once per component mount. * * @example * ```tsx * function Counter() { * const counterStore = useCreateStore({ count: 0 }) * const count = useSelector(counterStore, (state) => state.count) * const setState = useSetValue(counterStore) * * return ( * * ) * } * ``` */ export function useCreateStore( getValue: (prev?: NoInfer) => T, ): ReadonlyStore export function useCreateStore(initialValue: T): Store export function useCreateStore( initialValue: NonFunction, actions: StoreActionsFactory, ): Store export function useCreateStore( valueOrFn: T | ((prev?: T) => T), actions?: StoreActionsFactory, ): Store | Store | ReadonlyStore { const [store] = useState | Store | ReadonlyStore>( () => { if (typeof valueOrFn === 'function') { return createStore(valueOrFn as (prev?: NoInfer) => T) } if (actions) { return createStore(valueOrFn as NonFunction, actions) } return createStore(valueOrFn) }, ) return store }