useKeyPress
Events & gesturesA powerful React hook for detecting keyboard key presses, shortcuts, and combinations
Install
$ npm install @usefy/use-key-pressQuick start
import { useKeyPress } from "@usefy/use-key-press";
function Modal({ onClose }: { onClose: () => void }) {
const escapePressed = useKeyPress("Escape");
useEffect(() => {
if (escapePressed) onClose();
}, [escapePressed, onClose]);
return <div>Press Escape to close</div>;
}API reference
useKeyPress(target, options?)
Detects whether target is currently pressed and returns a boolean.
Parameters
| Parameter | Type | Description |
|---|---|---|
target | KeyPressTarget | The key(s) or predicate to detect (see below) |
options | UseKeyPressOptions | Optional configuration object |
target — KeyPressTarget
| Form | Example | Meaning |
|---|---|---|
string | "Escape", "ctrl+s" | A single key or a +-joined modifier combination |
string[] | ["ctrl+s", "meta+s"] | Alternative bindings — matches if any applies (OR) |
| predicate function | (e) => /^[0-9]$/.test(e.key) | Full control over matching |
Modifier aliases: ctrl/control, shift, alt/option/opt, meta/cmd/command/win, and mod (Ctrl on Windows/Linux, Cmd on macOS).
Key aliases: esc/escape, space, up/down/left/right (arrows), enter/return, del/delete, tab, backspace, plus, and more.
Options — UseKeyPressOptions
| Option | Type | Default | Description |
|---|---|---|---|
target | Window | Document | HTMLElement | RefObject | null | window | The element to attach listeners to. null detaches |
eventType | "keydown" | "keyup" | "both" | "both" | Which events drive the pressed state. "both" tracks the full held lifecycle |
enabled | boolean | true | When false, no listeners are attached and the result is always false |
preventDefault | boolean | false | Call event.preventDefault() on a match (e.g. override the browser's ctrl+s) |
stopPropagation | boolean | false | Call event.stopPropagation() on a match |
ignoreRepeat | boolean | true | Ignore auto-repeated keydown events for onPress (does not affect the returned boolean) |
ignoreInputElements | boolean | false | Ignore events from <input>, <textarea>, <select>, and contenteditable elements |
caseSensitive | boolean | false | Match letters case-sensitively (key mode only) |
matchBy | "key" | "code" | "key" | Match the logical key (event.key) or the physical key (event.code) |
exactModifiers | boolean | true | Require an exact modifier match. When true, "ctrl+s" does not match ctrl+shift+s |
onPress | (event: KeyboardEvent) => void | — | Called on a matching keydown, with the raw event |
onRelease | (event: KeyboardEvent) => void | — | Called when a matched key is released |
Returns
boolean — true while the target key/combination is pressed (with the default eventType: "both").
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.