Skip to content
Source
Sign inSign up
TanStack/store
Open History to see the last commit

useCreateStore.ts

65 lines1.9 KB

1import { useState } from 'preact/hooks'
2import { createStore } from '@tanstack/store'
3// eslint-disable-next-line no-duplicate-imports
4import type {
5 ReadonlyStore,
6 Store,
7 StoreActionMap,
8 StoreActionsFactory,
9} from '@tanstack/store'
10​
11type NonFunction<T> = T extends (...args: Array<any>) => any ? never : T
12​
13/**
14 * Creates a stable store instance for the lifetime of the component.
15 *
16 * Pass an initial value to create a writable store, or a getter function to
17 * create a readonly derived store. This mirrors {@link createStore}, but only
18 * creates the store once per component mount.
19 *
20 * @example
21 * ```tsx
22 * function Counter() {
23 * const counterStore = useCreateStore({ count: 0 })
24 * const count = useSelector(counterStore, (state) => state.count)
25 * const setState = useSetValue(counterStore)
26 *
27 * return (
28 * <button
29 * type="button"
30 * onClick={() => setState((state) => ({ ...state, count: state.count + 1 }))}
31 * >
32 * {count}
33 * </button>
34 * )
35 * }
36 * ```
37 */
38export function useCreateStore<T>(
39 getValue: (prev?: NoInfer<T>) => T,
40): ReadonlyStore<T>
41export function useCreateStore<T>(initialValue: T): Store<T>
42export function useCreateStore<T, TActions extends StoreActionMap>(
43 initialValue: NonFunction<T>,
44 actions: StoreActionsFactory<T, TActions>,
45): Store<T, TActions>
46export function useCreateStore<T, TActions extends StoreActionMap>(
47 valueOrFn: T | ((prev?: T) => T),
48 actions?: StoreActionsFactory<T, TActions>,
49): Store<T, TActions> | Store<T> | ReadonlyStore<T> {
50 const [store] = useState<Store<T, TActions> | Store<T> | ReadonlyStore<T>>(
51 () => {
52 if (typeof valueOrFn === 'function') {
53 return createStore(valueOrFn as (prev?: NoInfer<T>) => T)
54 }
55​
56 if (actions) {
57 return createStore(valueOrFn as NonFunction<T>, actions)
58 }
59​
60 return createStore(valueOrFn)
61 },
62 )
63​
64 return store