import { useState } from 'preact/hooks' import { createAtom } from '@tanstack/store' // eslint-disable-next-line no-duplicate-imports import type { Atom, AtomOptions, ReadonlyAtom } from '@tanstack/store' /** * Creates a stable atom instance for the lifetime of the component. * * Pass an initial value to create a writable atom, or a getter function to * create a readonly derived atom. This mirrors {@link createAtom}, but only * creates the atom once per component mount. * * @example * ```tsx * function Counter() { * const countAtom = useCreateAtom(0) * const [count, setCount] = useAtom(countAtom) * * return ( * * ) * } * ``` */ export function useCreateAtom( getValue: (prev?: NoInfer) => T, options?: AtomOptions, ): ReadonlyAtom export function useCreateAtom( initialValue: T, options?: AtomOptions, ): Atom export function useCreateAtom( valueOrFn: T | ((prev?: T) => T), options?: AtomOptions, ): Atom | ReadonlyAtom { const [atom] = useState | ReadonlyAtom>(() => { if (typeof valueOrFn === 'function') { return createAtom(valueOrFn as (prev?: NoInfer) => T, options) } return createAtom(valueOrFn, options) }) return atom }