HooksUtilities & Refs
useRefElement
Exposes a callback ref together with the element currently attached to it.
About
useRefElement bridges React's callback-ref API and state. It is useful when an effect or another hook needs the actual element as a reactive value.
Example
import { useRefElement } from "rooks";
export default function ElementStatus() {
const [buttonRef, button] = useRefElement<HTMLButtonElement>();
return (
<div>
<button type="button" ref={buttonRef}>
Focusable trigger
</button>
<p>Current tag: {button?.tagName ?? "not attached"}</p>
</div>
);
}Parameters
No parameters.
Return value
Returns [ref, element]:
ref: (element: T | null) => void— stable callback to pass to a Reactrefprop.element: T | null— current value last supplied by React; initiallynull.
Behavior and lifecycle
Attaching the ref stores the element in state and schedules a render. Detaching it stores null. If the ref moves between elements, consumers see the new node after React invokes the callback. The ref function itself is stable and owns no separate cleanup resource.
Compatibility and accessibility
During SSR no DOM element is attached, so element remains null. Guard every DOM operation for that state. The hook does not alter the attached element's semantics or accessible behavior.
Related
- useEventListenerRef uses this pattern to subscribe to an element event.