useEventListenerRef

About

A react hook to add an event listener to a ref

Examples

Basic usage

import { useState } from "react";
import { useEventListenerRef } from "rooks";
import "./styles.css";

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",
      }}
    >
      <h2>Click in this box</h2>
      <p> Value is {value}</p>
    </div>
  );
}

Arguments

ArgumentsTypeDescriptionDefault value
eventNamestringThe event to trackundefined
callbackFunctionThe callback to be called on event() => void
conditionsobjectThe options to be passed to the event listener
isLayoutEffectbooleanShould it use layout effect. Defaults to falsefalse

Return

Return valueTypeDescription
refFunctionA callback ref that can be used as ref prop

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel