Skip to content
On this page
Browser & DOMClient Component

useKeyPress

Overview

useKeyPress subscribes to keyboard events and matches modern key names, legacy numeric key codes, alternative lists, predicates, and string combinations such as ctrl+s or ctrl.s.

Signature

ts
function useKeyPress(
  keyFilter: KeyFilter,
  handler: KeyPressHandler,
  options?: UseKeyPressOptions,
): void;

Parameters

The default event is keydown. Use events for keyup or keypress, target/ref for a scoped EventTarget, exactMatch for strict modifiers, and enabled to pause. onError observes predicate or handler failures.

Returns

Nothing. The native subscription follows the target, event, and enabled options and is removed on cleanup.

Behavior

Key filters can be strings, numbers, arrays of alternatives, or predicates. Arrays always represent independent alternatives, so use 'ctrl+s' or 'ctrl.s' for a chord rather than ['ctrl', 's']. With exactMatch, undeclared modifier keys prevent a match. The handler receives the event and the matched string or numeric filter; a predicate may return that key explicitly. Matching callback errors are reported through onError and then rethrown; they are not swallowed.

SSR / RSC

No listener is attached when window or the configured target is unavailable. Use the Hook in a Client Component.

Example

Composition

Combine with useLockFn for keyboard-triggered mutations or useBoolean for modal and command-palette shortcuts.

Source

Read the implementation on GitHub.