Triggers a callback function whenever a specific keyboard key is pressed.
import { useEffect, useCallback } from "react";
interface KeyPressHook {
(key: string, callback: () => void): void;
}
const useKeyPress: KeyPressHook = function (key, callback) {
const eventHandler = useCallback((e: KeyboardEvent) => {
if (e.key === key) callback?.();
}, []);
useEffect(() => {
window.addEventListener("keyup", eventHandler);
return () => window.removeEventListener("keyup", eventHandler);
}, [key, callback]);
};
useKeyPress("Escape", onClickEscape);