useHotkey
A composable for handling hotkey combinations and sequences with platform-aware modifiers and automatic cleanup.
Usage
The useHotkey composable registers hotkey handlers on the window with automatic cleanup when the component is unmounted. It supports key combinations (ctrl+k), key sequences (g-h), and platform-aware modifier mapping.
Architecture
useHotkey builds on useEventListener for keyboard event handling:
Options
Key Aliases
Key strings are normalized before matching, so you can use human-friendly names instead of exact KeyboardEvent.key values:
| Alias | Canonical |
|---|---|
esc | escape |
return | enter |
del | delete |
space, spacebar | (space character) |
up / down / left / right | arrowup / arrowdown / arrowleft / arrowright |
control | ctrl |
command | cmd |
option | alt |
plus | + |
minus, hyphen | - |
slash | / |
underscore | _ |
// These are equivalent:
useHotkey('escape', close)
useHotkey('esc', close)
useHotkey('ctrl+plus', zoomIn) // matches Ctrl ++
useHotkey('cmd+minus', zoomOut) // matches Cmd +-Reactivity
| Property/Method | Reactive | Notes |
|---|---|---|
isActive | Computed from cleanup ref | |
isPaused | ShallowRef, readonly | |
keys | Accepts MaybeRefOrGetter, watched for changes |
Examples
FAQ
No. Modifier mapping is platform-aware, so a ctrl+k binding fires with Cmd on macOS. Write the combination once with ctrl and let the composable translate it.
By default useHotkey skips text inputs so shortcuts don’t hijack typing. Pass { inputs: true } on the binding to keep it active while focus is in an input — common for escape to close an open surface.
Use a hyphenated string: useHotkey('g-h', cb). The keys must be pressed in order, and the sequence resets after sequenceTimeout if you pause between keystrokes.
No. Keys are normalized before matching, so human-friendly aliases work — esc, return, del, space, up/down/left/right, command, option, and more. See the alias table above.
Yes. The keys argument accepts a ref or getter and is watched, so updating it re-registers the binding for the new combination — useful for user-customizable shortcuts.