UNPKG

react-use-current

Version:

A lightweight React hook for reactive state management.

49 lines (44 loc) 1.48 kB
import { Ref } from 'vref'; type Current<T> = Ref<T>; /** * React hook that creates a reactive ref-like state object. * * `useCurrent` wraps the `ref()` reactive system from `vref`. * The returned object has a mutable `.value`, and **any change to `.value`** * automatically triggers a React re-render — similar to `useState`, but using * a single reactive field instead of a setter function. * * Example: * ```tsx * const count = useCurrent(0); * * function handleIncrease() { * count.value += 1; // reactive update → re-render * } * * return ( * <button onClick={handleIncrease}> * Count: {count.value} * </button> * ); * ``` * * @param initial Optional initial value. * @returns A reactive `Ref<T>` object with a `.value` property. */ declare function useCurrent<T>(initial: T): Current<T>; declare function useCurrent<T = undefined>(): Current<T | undefined>; /** * Returns a symbol to track a reactive ref in React dependency arrays. * Use with useEffect or useMemo to respond to changes without recreating objects. * * @param target - A reactive ref from useCurrent, or any value. * @returns A symbol for reactive refs, or the original value if non-reactive. * * Example: * useEffect(() => { ... }, [track(user)]); * const isAdult = useMemo(() => user.value.age >= 18, [track(user.value.age)]); */ declare function track<T>(target: T): symbol | T; export { useCurrent as default, track }; export type { Current };