react-usekit

Beta

useEventListener

A custom hook that adds an event listener to a specified element or the window.

Installation

npx react-usekit@latest init

Select: hooks → TypeScript or JavaScript → path -> useEventListener

Usage

import useEventListener from "./hooks/useEventListener";
import { useState } from "react";

function App() {
  const [lastKey, setLastKey] = useState("");

  useEventListener("keydown", (event) => {
    setLastKey(event.key);
  });

  return (
    <div>
      <p>Press any key...</p>
      <p>Last key pressed: {lastKey}</p>
    </div>
  );
}

API

Parameters

ParameterTypeDescription
eventNamestringThe name of the event to listen for
handler(event: Event) => voidThe function to call when the event is triggered
elementRefObject<T> | undefinedThe element to attach the listener to. Defaults to window
optionsboolean | AddEventListenerOptionsOptions for the event listener

Returns

This hook doesn't return anything. dependencies change.