Skip to Content
⭐️ Leave a star →
HooksuseKeyboard

useKeyboard

Subscribes to keyboard events with a map of key → handler. Keys are matched against event.key (case-insensitive). Pass a tuple to require specific modifier keys, and to opt into preventDefault / stopPropagation.

By default the listener is attached to window, but you can pin it to a specific element via the target option.

import { useRef } from 'react' import { useKeyboard } from '@wire-ui/react' function CommandPalette({ onSave, onClose }: { onSave: () => void; onClose: () => void }) { const inputRef = useRef<HTMLInputElement>(null) useKeyboard({ Escape: onClose, s: [onSave, { meta: true, preventDefault: true }], Enter: [() => console.log('submit'), { preventDefault: true }], }, { target: inputRef, event: 'keydown', }) return <input ref={inputRef} placeholder="⌘S to save, Esc to close" /> }

Parameters

ParamTypeDescription
mapKeyboardMapObject of key → handler or key → [handler, options].
optionsUseKeyboardOptionsSee below.

KeyboardMap

type KeyHandler = (event: KeyboardEvent) => void interface KeyboardHandlerOptions { ctrl?: boolean meta?: boolean shift?: boolean alt?: boolean preventDefault?: boolean stopPropagation?: boolean } type KeyboardMap = Record<string, KeyHandler | [KeyHandler, KeyboardHandlerOptions]>

Modifier flags use exact match{ meta: true } only fires when Meta is held and won’t match plain key presses. Omit a modifier to ignore its state.

Options

OptionTypeDefaultDescription
targetRefObject<HTMLElement | null> | HTMLElement | Window | Document | nullwindowElement to attach the listener to.
event'keydown' | 'keyup' | 'keypress''keydown'Which keyboard event to listen on.
enabledbooleantrueToggle the listener without unmounting.
Last updated on

MIT License © 2026 wire-ui

useKeyboard – Wire UI