Rooks
HooksKeyboard & Input

useKeyBindings

Maps independent keyboard identifiers to their callbacks.

About

useKeyBindings creates one useKey subscription per property in a key-to-callback object. Each property is an independent binding, not part of a chord.

Example

import { useMemo, useState } from "react";
import { useKeyBindings } from "rooks";

export default function ArrowStepper() {
  const [value, setValue] = useState(0);
  const bindings = useMemo(
    () => ({
      ArrowUp: () => setValue((current) => current + 1),
      ArrowDown: () => setValue((current) => current - 1),
    }),
    []
  );

  useKeyBindings(bindings);

  return <p>Use Arrow Up or Arrow Down: {value}</p>;
}

Parameters

  • keyBindings: a string-keyed object whose values are (event: KeyboardEvent) => void.
  • 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 all bindings; defaults to true.

The binding and options types are private and are shown inline.

Return value

The hook returns void.

Behavior and lifecycle

Each enumerable binding calls useKey, so its identifier matches key, code, or legacy numeric event fields. Because hooks are created inside the property loop, the number and order of keys must stay constant across renders. Build a stable binding object rather than conditionally adding or removing properties. Each underlying listener is cleaned up when disabled, reconfigured, or unmounted.

Compatibility and accessibility

The hook is browser-only. Do not replace standard typing, navigation, or assistive-technology shortcuts. Show discoverable controls for every shortcut and scope bindings to the smallest practical target.

  • useKey handles one independent binding.
  • useKeys detects a true multi-key chord.

On this page