useKeyDown
React hook to listen for key presses and keyboard shortcuts with modifier combos, element scoping, and typed callbacks.
Demo
Q
W
E
A
S
D
Press an arrow key
Sidebar is closed (CtrlOrCmd+B)
Sidebar is closed (CtrlOrCmd+B)
Usage
Single key or array of keys:
Key combos and modifier shortcuts:
Object form with preventDefault:
Scoped to a specific element:
Parameters
| Parameter | Type | Description |
|---|---|---|
keys | K | readonly K[] | Single key, key combination, or an array of keys / combos to listen for. |
callback | (event: KeyboardEvent, key: K) => void | Simple form. Called when a matching key combination is pressed. |
Object form second argument:
| Property | Type | Default | Description |
|---|---|---|---|
onKeyDown | (event: KeyboardEvent, key: K) => void | — | Callback fired when a matching key is pressed. |
preventDefault | boolean | false | When true, automatically calls event.preventDefault() on match. |
Return Values
Returns a React.RefObject<T>. When attached to an element, the keyboard listener is scoped to that element. When unused, it listens globally on window.
Key Combos & Modifiers
Combine modifier keys with + syntax:
| Modifier Alias | Description |
|---|---|
Ctrl / Control | Control key |
Shift | Shift key |
Alt / Opt / Option | Alt / Option key |
Meta / Cmd / Command | Command (Mac) or Windows key |
CtrlOrCmd | Ctrl on Windows/Linux, Cmd on macOS |
AltOrCmd | Alt on Windows/Linux, Cmd on macOS |
space | Space bar |