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
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. dependencies change.