Rooks
Utilities & Refs

useRefElement

Returns a ref and a state variable that is updated when the ref is attached.

About

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

Examples

Attach an event listener to the current element

import { useEffect, useState } from "react";
import { useRefElement } from "rooks";

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;
}

export default function App() {
  const [value, setValue] = useState(0);
  const ref = useEventListenerRef("click", function () {
    setValue(value + 1);
  });

  return (
    <div
      ref={ref}
      className="App"
      style={{
        padding: "20px",
        border: "5px solid dodgerblue",
      }}
    >
      <h1>useRefElement Example</h1>
      <h2>Click in this box</h2>
      <p> Value is {value}</p>
    </div>
  );
}

Read the current element from the callback ref

import { useRefElement } from "rooks";

export default function CurrentElementPreview() {
  const [ref, element] = useRefElement();

  return (
    <div>
      <button ref={ref}>Focusable trigger</button>
      <p>Current tag: {element?.tagName ?? "none"}</p>
    </div>
  );
}

Arguments

No arguments.

Returns an array of two items

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

On this page