import type { Dispatch, MutableRef, StateUpdater } from "../dependencies/types"; import { EMPTY_ARRAY, useCallback, useRef, useState } from "../dependencies.js"; type ReferenceStateResult = readonly [ MutableRef, Dispatch>, ]; /** * Same as `useState`, but returns the value in a reference to use it in callbacks without having to regenerate them. * * @param value Initial value. * @returns A couple containing the reference to the current state value, and the state updater function. */ export function useReferencedState( value: T | (() => T), ): ReferenceStateResult; export function useReferencedState(): ReferenceStateResult< T | undefined >; export function useReferencedState( value?: T | (() => T), ): ReferenceStateResult { const { 0: state, 1: setState } = useState(value); const stateRef = useRef(state); const onChangeStateRef = useCallback>>( (value) => { const nextValue = typeof value === "function" ? (value as any)(stateRef.current) : value; stateRef.current = nextValue; setState(() => nextValue); }, EMPTY_ARRAY, ); return [stateRef, onChangeStateRef]; }