Open History to see the last commit
1'use client'
2β
3import { useState } from 'react'
4import { createStore } from '@tanstack/store'
5import type {
6 ReadonlyStore,
7 Store,
8 StoreActionMap,
9 StoreActionsFactory,
10} from '@tanstack/store'
11β
12type NonFunction<T> = T extends (...args: Array<any>) => any ? never : T
13β
14/**
15 * Creates a stable store instance for the lifetime of the component.
16 *
17 * Pass an initial value to create a writable store, or a getter function to
18 * create a readonly derived store. This hook mirrors the overloads from
19 * {@link createStore}, but ensures the store is only created once per mount.
20 *
21 * @example
22 * ```tsx
23 * const counterStore = useCreateStore({ count: 0 })
24 * ```
25 */
26export function useCreateStore<T>(
27 getValue: (prev?: NoInfer<T>) => T,
28): ReadonlyStore<T>
29export function useCreateStore<T>(initialValue: T): Store<T>
30export function useCreateStore<T, TActions extends StoreActionMap>(
31 initialValue: NonFunction<T>,
32 actions: StoreActionsFactory<T, TActions>,
33): Store<T, TActions>
34export function useCreateStore<T, TActions extends StoreActionMap>(
35 valueOrFn: T | ((prev?: T) => T),
36 actions?: StoreActionsFactory<T, TActions>,
37): Store<T, TActions> | Store<T> | ReadonlyStore<T> {
38 const [store] = useState<Store<T, TActions> | Store<T> | ReadonlyStore<T>>(
39 () => {
40 if (typeof valueOrFn === 'function') {
41 return createStore(valueOrFn as (prev?: NoInfer<T>) => T)
42 }
43β
44 if (actions) {
45 return createStore(valueOrFn as NonFunction<T>, actions)
46 }
47β
48 return createStore(valueOrFn)
49 },
50 )
51β
52 return store
53}