UNPKG

reactuals

Version:

A useful package providing a collection of 50+ React hooks and utilities to simplify React development.

18 lines (17 loc) 595 B
import { useEffect } from "react"; /** * Detect when a specific keyboard key is pressed. * @param targetKey - The key to listen for (e.g. "Enter", "Escape") * @param handler - Function to call when key is pressed */ export function useKeyPress(targetKey, handler) { useEffect(() => { const keyListener = (event) => { if (event.key === targetKey) { handler(event); } }; window.addEventListener("keydown", keyListener); return () => window.removeEventListener("keydown", keyListener); }, [targetKey, handler]); }