import { useState } from 'react' import { createStore } from '@tanstack/store' 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 hook mirrors the overloads from * {@link createStore}, but ensures the store is only created once per mount. * * @example * ```tsx * const counterStore = useCreateStore({ count: 0 }) * ``` */ 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 }