ReactUseKit

useEventListener

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

Installation

pnpm dlx shadcn@latest add @reactusekit/use-event-listener

Usage

import { useEventListener } from "@/hooks/use-event-listener"
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.