import type { AtomToken, RegularAtomFamilyToken, RegularAtomToken, } from "atom.io" import type { Canonical } from "atom.io/foundations/canonical" import { findInStore, setIntoStore } from "atom.io/internal" import { useContext, useEffect } from "react" import { StoreContext } from "./store-context.tsx" export function useAtomicRef( token: RegularAtomToken, useRef: (initialValue: TT | null) => R, ): R export function useAtomicRef< T, K extends Canonical, R extends { current: T | null }, >( token: RegularAtomFamilyToken, key: NoInfer, useRef: (initialValue: TT | null) => R, ): R export function useAtomicRef< T, K extends Canonical, R extends { current: T | null }, >( ...params: | [ RegularAtomFamilyToken, NoInfer, (initialValue: TT | null) => R, ] | [RegularAtomToken, (initialValue: TT | null) => R] ): R { let token: AtomToken let useRef: (initialValue: TT | null) => R const store = useContext(StoreContext) if (params.length === 3) { const family = params[0] const key = params[1] token = findInStore(store, family, key) useRef = params[2] } else { token = params[0] useRef = params[1] } const ref = useRef(null) useEffect(() => { setIntoStore(store, token, ref.current) }, [token]) return ref }