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
Parameter | Type | Description |
---|---|---|
eventName | string | The name of the event to listen for |
handler | (event: Event) => void | The function to call when the event is triggered |
element | RefObject<T> | undefined | The element to attach the listener to. Defaults to window |
options | boolean | AddEventListenerOptions | Options for the event listener |
Returns
This hook doesn't return anything.