Skip to content

useKeyStroke

Easy and intuitive way of declaring keydown events to specific keys.

Installation

npx rabbithook@latest add use-key-stroke

Usage

App.tsx
import useKeyStroke from "@/hooks/use-key-stroke";
function Component() {
useKeyStroke("ArrowUp", () => {
console.log("ArrowUp key pressed");
});
useKeyStroke(["W", "w", "ArrowUp"], () => {
console.log("Any of the specified keys were pressed");
});
return ();
}

Code

use-key-stroke.ts
import useEventListener from "../use-event-listener";
type IKeyStrokeKey = string | string[];
type IKeyStrokeHandler = (e: KeyboardEvent) => void;
function useKeyStroke(key: IKeyStrokeKey, handler: IKeyStrokeHandler) {
useEventListener("keydown", (e) => {
const keys = Array.isArray(key) ? key : [key];
if (keys.includes(e.key)) {
handler(e);
}
});
}
export default useKeyStroke;