Skip to main content
Version: 5.9.0

useRefElement

About​

Helps bridge gap between callback ref and state. Manages the element called with callback ref api using state variable.

Installation​

npm install --save rooks

Importing the hook​

import { useRefElement } from "rooks";

Usage​

// Build a useEventListenerRef hook using useRefElement
function useEventListenerRef(eventName, callback) {
const [ref, element] = useRefElement();

useEffect(() => {
if (!(element && element.addEventListener)) {
return;
}
element.addEventListener(eventName, callback);
return () => {
element.removeEventListener(eventName, callback);
};
}, [element, eventName, callback]);

return ref;
}

Arguments​

No arguments.

Returns an array of two items​

Returned itemsTypeDescription
ref(refElement: RefElementOrNull<T>) => voidThe callback ref
elementRefElementOrNull<T>The element linked to the ref

Codesandbox Example​

Basic usage​

Join Bhargav's discord server​

You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.