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: onestring | number, or an array. Each identifier is compared withevent.key,code,keyCode,which, andcharCode.callback(event): receives the matching nativeKeyboardEvent.options.eventTypes: an array of"keydown" | "keypress" | "keyup"; defaults to["keydown"].options.target: optional object ref to anHTMLElement; defaults towindow.options.when: enables listeners; defaults totrue.
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.
Related
- useKeys detects a simultaneous key combination.
- useKeyRef returns a callback ref target.
- useKeyBindings maps several independent keys to handlers.