Rooks
HooksKeyboard & Input

useKeyRef

Returns a callback ref that handles matching keyboard events on an element.

About

useKeyRef listens on the element assigned to its callback ref. One identifier or any identifier in an array can match; arrays do not represent chords.

Example

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

export default function EnterCounter() {
  const [count, setCount] = useState(0);
  const keyRef = useKeyRef("Enter", () => {
    setCount((value) => value + 1);
  });

  return (
    <label>
      Press Enter here
      <input ref={keyRef} />
      <span>Matches: {count}</span>
    </label>
  );
}

Parameters

  • keys: one string | number, or an array matched against key, code, keyCode, which, and charCode.
  • callback(event): receives the native KeyboardEvent.
  • options.eventTypes: an array of "keydown" | "keypress" | "keyup"; defaults to ["keydown"].
  • options.when: enables listeners; defaults to true.

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

Return value

The hook returns a callback ref that accepts an HTMLElement | null.

Behavior and lifecycle

Assigning the ref changes the native event target. The latest callback is retained through a ref. One listener is added per configured event type and all listeners are removed when the target changes, the hook is disabled, or the component unmounts.

Compatibility and accessibility

The hook installs listeners only in the browser. The target must be focusable to receive ordinary keyboard events. Prefer native controls, preserve their default behavior unless there is a clear reason not to, and never hide the only action behind a shortcut.

  • useKey accepts an object ref or listens on window.
  • useKeys detects simultaneous identifiers.

On this page