"use client"; import type { Ref, RefCallback, RefObject } from "react"; import { useCallback, useRef } from "react"; import { applyRef } from "./utils/applyRef.js"; /** * @since 2.3.0 * @internal */ export type EnsuredRefs = readonly [ RefObject, RefCallback, ]; /** * This is mostly an internal hook that allows for an optional ref (normally * from props or hook options) to be merged with a hook's required `ref`. This * will return a RefObject used for DOM manipulation in a custom hook * followed by a ref callback function that should be passed to the DOM node * that will ensure that both the optional `propRef` and hook ref are updated. * * @example Simple Example * ```tsx * import { useEnsuredRef } from "@react-md/core/useEnsuredRef"; * import { HTMLAttributes, forwardRef } from "react"; * * export type ExampleProps = HTMLAttributes; * * export const Example = forwardRef(function Example(props, ref) { * const [nodeRef, refHandler] = useEnsuredRef(ref); * useEffect(() => { * // do something with nodeRef.current * }, [nodeRef]) * * return
; * }); * ``` * * @since 2.3.0 * @internal */ export function useEnsuredRef( propRef?: Ref ): EnsuredRefs { const ref = useRef(null); const refHandler = useCallback( (instance: E | null) => { applyRef(instance, propRef); ref.current = instance; }, [propRef] ); return [ref, refHandler]; }