useEventListener

React hook for handling keyboard events.

Installation

npm install @mvdlei/hooks

Example

Click anywhere! 0

Usage

import React from "react";
import { useEventListener } from "@mvdlei/hooks";
 
const App = () => {
  const [state, setState] = React.useState(0);
  useEventListener("click", () => {
    setState((prev) => prev + 1);
  });
 
  return (
    <div className={cn("relative rounded font-mono text-sm mt-2", className)} {...props}>
      Click anywhere! {state}
    </div>
  );
};

Reference

useEventListener<
  KW extends keyof WindowEventMap,
  KH extends keyof HTMLElementEventMap,
  KM extends keyof MediaQueryListEventMap,
  T extends HTMLElement | MediaQueryList | void = void,
>(
  eventName: KW | KH | KM,
  handler: (
    event:
      | WindowEventMap[KW]
      | HTMLElementEventMap[KH]
      | MediaQueryListEventMap[KM]
      | Event,
  ) => void,
  element?: RefObject<T>,
  options?: boolean | AddEventListenerOptions,
): void;

use-event-listener.ts