Rooks
HooksKeyboard & Input

useKey

Calls a callback when any configured keyboard identifier matches an event.

About

useKey listens for one key identifier or any identifier in a list. A list means “match any,” not “hold all keys together”; use useKeys for a chord.

Example

import { useState } from "react";
import { useKey } from "rooks";

export default function EscapeStatus() {
  const [open, setOpen] = useState(true);

  useKey("Escape", () => setOpen(false), { when: open });

  return (
    <div>
      <button onClick={() => setOpen(true)}>Open</button>
      <p>{open ? "Press Escape to close" : "Closed"}</p>
    </div>
  );
}

Parameters

  • keys: one string | number, or an array. Each identifier is compared with event.key, code, keyCode, which, and charCode.
  • callback(event): receives the matching native KeyboardEvent.
  • options.eventTypes: an array of "keydown" | "keypress" | "keyup"; defaults to ["keydown"].
  • options.target: optional object ref to an HTMLElement; defaults to window.
  • options.when: enables listeners; defaults to true.

The options type is private and is not importable from rooks.

Return value

The hook returns void.

Behavior and lifecycle

The latest callback is stored in a ref. The hook adds one listener for each event type and removes them when disabled, reconfigured, or unmounted. If a supplied target ref is null when the effect runs, no fallback listener is attached. Use useKeyRef when the target must be discovered through a callback ref.

Compatibility and accessibility

No listener is attached during server rendering. Keyboard identifiers vary by layout: key represents the user's character while code represents a physical key. Do not override established browser or assistive-technology shortcuts, and keep equivalent visible controls available.

On this page