Skip to content
usefy

useKeyPress

Events & gestures

A powerful React hook for detecting keyboard key presses, shortcuts, and combinations

Install

$ npm install @usefy/use-key-press

Quick start

useKeyPress.tsx
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

ParameterTypeDescription
targetKeyPressTargetThe key(s) or predicate to detect (see below)
optionsUseKeyPressOptionsOptional configuration object

targetKeyPressTarget

FormExampleMeaning
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

OptionTypeDefaultDescription
targetWindow | Document | HTMLElement | RefObject | nullwindowThe element to attach listeners to. null detaches
eventType"keydown" | "keyup" | "both""both"Which events drive the pressed state. "both" tracks the full held lifecycle
enabledbooleantrueWhen false, no listeners are attached and the result is always false
preventDefaultbooleanfalseCall event.preventDefault() on a match (e.g. override the browser's ctrl+s)
stopPropagationbooleanfalseCall event.stopPropagation() on a match
ignoreRepeatbooleantrueIgnore auto-repeated keydown events for onPress (does not affect the returned boolean)
ignoreInputElementsbooleanfalseIgnore events from <input>, <textarea>, <select>, and contenteditable elements
caseSensitivebooleanfalseMatch letters case-sensitively (key mode only)
matchBy"key" | "code""key"Match the logical key (event.key) or the physical key (event.code)
exactModifiersbooleantrueRequire an exact modifier match. When true, "ctrl+s" does not match ctrl+shift+s
onPress(event: KeyboardEvent) => voidCalled on a matching keydown, with the raw event
onRelease(event: KeyboardEvent) => voidCalled when a matched key is released

Returns

booleantrue 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.

More in events & gestures