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

useCreateAtom.ts

40 lines1.1 KB

1'use client'
2​
3import { useState } from 'react'
4import { createAtom } from '@tanstack/store'
5import type { Atom, AtomOptions, ReadonlyAtom } from '@tanstack/store'
6​
7/**
8 * Creates a stable atom instance for the lifetime of the component.
9 *
10 * Pass an initial value to create a writable atom, or a getter function to
11 * create a readonly derived atom. This hook mirrors the overloads from
12 * {@link createAtom}, but ensures the atom is only created once per mount.
13 *
14 * @example
15 * ```tsx
16 * const countAtom = useCreateAtom(0)
17 * ```
18 */
19export function useCreateAtom<T>(
20 getValue: (prev?: NoInfer<T>) => T,
21 options?: AtomOptions<T>,
22): ReadonlyAtom<T>
23export function useCreateAtom<T>(
24 initialValue: T,
25 options?: AtomOptions<T>,
26): Atom<T>
27export function useCreateAtom<T>(
28 valueOrFn: T | ((prev?: T) => T),
29 options?: AtomOptions<T>,
30): Atom<T> | ReadonlyAtom<T> {
31 const [atom] = useState<Atom<T> | ReadonlyAtom<T>>(() => {
32 if (typeof valueOrFn === 'function') {
33 return createAtom(valueOrFn as (prev?: NoInfer<T>) => T, options)
34 }
35​
36 return createAtom(valueOrFn, options)
37 })
38​
39 return atom