# useHotkey (/docs/hooks/use-hotkey)





`useHotkey` calls a handler when a keyboard shortcut is pressed. It's the hook behind [Spotlight](/docs/spotlight)'s ⌘K.

```tsx
import { useHotkey } from '@42-central/ui-react';

useHotkey('mod+s', () => save());
useHotkey(['j', 'arrowdown'], next, { scope: list, repeat: true });
```

The matched event's default is prevented, so the browser's own shortcut on the same keys (⌘S's Save dialog) doesn't also run. Pass `false` instead of a key to bind nothing, e.g. while a feature is off.

## Matching [#matching]

A hotkey is modifiers and a key joined with `+`, the key last: `"mod+k"`, `"shift+mod+p"`, `"alt+/"`.

* **`mod`** is ⌘ on Apple platforms and Ctrl elsewhere, the usual convention for app shortcuts. `meta` (`cmd`, `command`), `ctrl` (`control`), `alt` (`option`) and `shift` name one key explicitly.
* **Modifiers match exactly.** `mod+k` doesn't fire on ⌘⇧K, and `k` doesn't fire on ⌘K.
* **The key follows the keyboard layout.** It's compared case-insensitively with `event.key`, so `"mod+z"` is the key that types *z* on an AZERTY keyboard too. Name special keys as `event.key` does: `enter`, `escape`, `arrowdown`, `backspace`, `delete`, `tab`; the space bar is `space` and the plus key is a trailing `+` (`"mod++"`).
* **A modifier can be the key**: `"alt"` fires when ⌥ itself is pressed (or released, with `event: "keyup"`).
* **IME composition is ignored**, so confirming a Japanese or Chinese candidate with ↵ doesn't fire an `enter` hotkey.
* **A misspelled modifier binds nothing.** `"ctl+k"` matches no key at all, rather than firing on a bare `k`, and warns in development.

## When it fires [#when-it-fires]

By default a hotkey fires anywhere on the page, unless an overlay is open above the component that bound it, the key is an auto-repeat, or a component already handled the event. In a text field, a ⌘/Ctrl/Alt hotkey fires too, and a bare-key one (`/`, `?`, `j`) doesn't, so typing it types the character. The options below narrow or widen that.

### Anywhere [#anywhere]

The default for a ⌘/Ctrl/Alt hotkey, an app-wide command like ⌘K or ⌘S. It also fires while typing, since such a shortcut can't type a character. `inputs: "allow"` (or `true`) gives a bare key the same reach.

<Preview code="&#x22;const [count, setCount] = useState(0);\nuseHotkey('mod+j', () => setCount((value) => value + 1));\n\n<Kbd hotkey=\&#x22;mod+j\&#x22; />\n<TextInput aria-label=\&#x22;Any field\&#x22; placeholder=\&#x22;Focus me, then press it\&#x22; />\n<p>Pressed: {count}</p>&#x22;">
  <HotkeyAnywhereDemo />
</Preview>

### Outside text fields [#outside-text-fields]

`inputs: "ignore"` (or `false`) keeps a hotkey out of text fields. It's already the default for a bare key or a `shift+` one: a `/` or `?` would otherwise swallow the character being typed ([WCAG 2.1.4](https://www.w3.org/WAI/WCAG22/Understanding/character-key-shortcuts.html)). A text field is a text `<input>`, a `<textarea>` or a `contenteditable`. Buttons, checkboxes, sliders and selects are not text fields: to yield to those, use [`when`](#native-controls).

<Preview code="&#x22;const search = useRef<HTMLInputElement>(null);\nuseHotkey('/', () => search.current?.focus(), { inputs: 'ignore' });\n\n<TextInput ref={search} aria-label=\&#x22;Search\&#x22; placeholder=\&#x22;Search…\&#x22; />&#x22;">
  <HotkeyOutsideFieldsDemo />
</Preview>

### Only in text fields [#only-in-text-fields]

`inputs: "only"` is the reverse: ⌘↵ to send a comment, Esc to clear a search box. Add a `scope` so it fires only in *that* field.

<Preview code="&#x22;const field = useRef<HTMLTextAreaElement>(null);\nuseHotkey('mod+enter', send, { inputs: 'only', scope: field });\n\n<Textarea ref={field} aria-label=\&#x22;Comment\&#x22; placeholder=\&#x22;Write a comment…\&#x22; />&#x22;">
  <HotkeyOnlyInFieldsDemo />
</Preview>

### Inside an element [#inside-an-element]

`scope` takes a ref: the hotkey fires only while focus is inside that element, like ⌘A selecting a table's rows rather than the page. A scope that is `inert` or `hidden`, itself or through an ancestor (a closed [Collapse](/docs/collapse), an inactive [Tabs](/docs/tabs) panel), counts as outside.

This demo also passes `repeat: true`: holding <Kbd size="sm">J</Kbd> keeps moving down. Auto-repeat is off by default, since a held key toggling or deleting something thirty times a second is the costly surprise; a skipped repeat still has its default prevented.

<Preview code="&#x22;const list = useRef<HTMLDivElement>(null);\nuseHotkey(['j', 'arrowdown'], () => move(1), { scope: list, repeat: true });\nuseHotkey(['k', 'arrowup'], () => move(-1), { scope: list, repeat: true });\n\n<div ref={list} role=\&#x22;listbox\&#x22; tabIndex={0}>…</div>&#x22;">
  <HotkeyScopeDemo />
</Preview>

### Under the pointer [#under-the-pointer]

With `hover`, the pointer resting on the scope counts as being inside it, no focus needed: hover a row, press a key to act on that row.

<Preview code="&#x22;function Row({ title, onArchive }) {\n  const row = useRef<HTMLLIElement>(null);\n  useHotkey('e', onArchive, { scope: row, hover: true });\n\n  return <li ref={row}>{title} <Kbd hotkey=\&#x22;e\&#x22; /></li>;\n}&#x22;">
  <HotkeyHoverDemo />
</Preview>

### Not under an overlay [#not-under-an-overlay]

`layer` is on by default: a hotkey goes quiet while a [Modal](/docs/modal), [Drawer](/docs/drawer), [Popover](/docs/popover) or a picker's list is open above the component that bound it. A page's `j` stops counting while the modal is open; the modal's own `j` takes over, and goes quiet in turn while a nested modal is open above it.

It's read from React context, not the DOM, so it follows the component tree through portals: what counts is what opened *from* the component's layer. A hotkey that must also reach the overlay it opened (a toggle like Spotlight's ⌘K) passes `layer: false`.

<Preview code="&#x22;function Page() {\n  const [open, setOpen] = useState(false);\n  useHotkey('j', countOnThePage); // quiet while the modal is open\n\n  return (\n    <Modal open={open} onOpenChange={setOpen} title=\&#x22;Layered hotkeys\&#x22;>\n      <ModalCounter /> {/* its own useHotkey('j', …) fires */}\n    </Modal>\n  );\n}&#x22;">
  <HotkeyLayerDemo />
</Preview>

### Hold and release [#hold-and-release]

`event: "keyup"` fires on release. Pair it with a keydown hotkey on the same key for hold-to-peek or push-to-talk.

<Preview code="&#x22;const [peeking, setPeeking] = useState(false);\nuseHotkey('alt', () => setPeeking(true));\nuseHotkey('alt', () => setPeeking(false), { event: 'keyup' });\n\n<Button>New issue {peeking && <Kbd hotkey=\&#x22;c\&#x22; />}</Button>&#x22;">
  <HotkeyHoldDemo />
</Preview>

### Native controls [#native-controls]

`when` has the last word on a matched event, after every other option. Its default skips an event a component already handled (`event.defaultPrevented`: Select's ↵, a dialog's Esc). A `when` of your own **replaces** that default, so keep the check unless the hotkey should run even then:

```tsx
// Leave Space to a focused button or checkbox.
useHotkey('space', togglePlay, {
  when: (event) =>
    !event.defaultPrevented &&
    !(event.target instanceof Element && event.target.closest('button, [role="checkbox"]')),
});

// Also fire on events a component already handled.
useHotkey('escape', closePanel, { when: () => true });
```

## Labels [#labels]

`hotkeyKeys` lists a hotkey's keys the way the platform writes them, one label per key cap: `"mod+k"` is `["⌘", "K"]` on Apple platforms and `["Ctrl", "K"]` elsewhere. Modifiers come in Apple's order (⌃⌥⇧⌘) whatever order the string names them in. `formatHotkey` joins that list into one string for plain-text places, a `title` or a tooltip: `⌘K` / `Ctrl K`, `⇧⌘P` / `Ctrl Shift P`.

```tsx
import { formatHotkey, hotkeyKeys } from '@42-central/ui-react';

hotkeyKeys('mod+shift+p', true); // ["⇧", "⌘", "P"]
hotkeyKeys('mod+shift+p', false); // ["Ctrl", "Shift", "P"]
formatHotkey('mod+shift+p', true); // "⇧⌘P"
formatHotkey('mod+shift+p', false); // "Ctrl Shift P"
```

Both take [`Kbd`'s `translations`](/docs/kbd#translations) as an optional third argument, merged per key onto the English words, so a tooltip and the caps beside it read the same:

```tsx
const german = { ctrl: 'Strg', del: 'Entf' };

formatHotkey('mod+shift+delete', false, german); // "Strg Shift Entf"
formatHotkey('mod+shift+delete', true, german); // "⇧⌘⌦": Apple's glyphs aren't words
<Kbd hotkey="mod+shift+delete" translations={german} />;
```

The platform defaults to the visitor's, which a server can't know. While rendering, pass [`useApplePlatform()`](/docs/hooks/use-apple-platform) (`false` on the server and during hydration, the real answer right after) so the server markup and the first client render agree. On screen, let [`Kbd`](/docs/kbd#from-a-hotkey) do it: `<Kbd hotkey="mod+k" />` draws one cap per key, with an icon for each key that has one.

`matchHotkey(hotkey, event)` is the matcher on its own, for a handler you attach yourself:

```tsx
import { matchHotkey } from '@42-central/ui-react';

<input onKeyDown={(event) => matchHotkey('mod+enter', event) && submit()} />;
```

## API [#api]

### Parameters [#parameters]

<TypeTable
  type="{
  keys: {
    type: 'string | string[] | false',
    required: true,
    description: 'The hotkey, or several that run the same handler. false (or undefined) binds nothing.',
  },
  handler: {
    type: '(event: KeyboardEvent) => void',
    required: true,
    description: 'Called with the matched event. The latest handler always runs, without rebinding.',
  },
  options: {
    type: 'HotkeyOptions',
    description: 'When the hotkey fires; see below.',
  },
}"
/>

### Options [#options]

<TypeTable
  type="{
  inputs: {
    type: '&#x22;allow&#x22; | &#x22;ignore&#x22; | &#x22;only&#x22; | boolean',
    default: '&#x22;allow&#x22; for ⌘/Ctrl/Alt, else &#x22;ignore&#x22;',
    description:
      'Whether it fires while typing in a text field (a text input, textarea or contenteditable): anywhere, not while typing, or only while typing. true is &#x22;allow&#x22;, false is &#x22;ignore&#x22;. In an array, each hotkey gets its own default.',
  },
  scope: {
    type: 'RefObject<Element | null>',
    description:
      'Fire only while focus is inside this element. An inert or hidden scope (or one inside an inert or hidden ancestor) counts as outside.',
  },
  hover: {
    type: 'boolean',
    default: 'false',
    description: 'With scope: the pointer resting on the scope counts as being inside it.',
  },
  layer: {
    type: 'boolean',
    default: 'true',
    description:
      'Yield while a Modal, Drawer, Popover or picker is open above the component that bound the hotkey.',
  },
  repeat: {
    type: 'boolean',
    default: 'false',
    description: &#x22;Also fire on a held key's auto-repeats. A skipped repeat still has its default prevented.&#x22;,
  },
  event: {
    type: '&#x22;keydown&#x22; | &#x22;keyup&#x22;',
    default: '&#x22;keydown&#x22;',
    description: 'Fire on press, or on release.',
  },
  when: {
    type: '(event: KeyboardEvent) => boolean',
    default: '(event) => !event.defaultPrevented',
    description:
      'The last word on a matched event. Replaces the default, which skips events a component already handled.',
  },
}"
/>

### Helpers [#helpers]

<TypeTable
  type="{
  hotkeyKeys: {
    type: '(hotkey: string, apple?: boolean, translations?: Partial<KbdTranslations>) => string[]',
    description: &#x22;The hotkey's keys, one label per cap: [\&#x22;⌘\&#x22;, \&#x22;K\&#x22;] on Apple platforms, [\&#x22;Ctrl\&#x22;, \&#x22;K\&#x22;] elsewhere. apple defaults to the current platform; translations replaces the English key words per key, as on <Kbd hotkey>.&#x22;,
  },
  formatHotkey: {
    type: '(hotkey: string, apple?: boolean, translations?: Partial<KbdTranslations>) => string',
    description: &#x22;hotkeyKeys as one string, for plain text: ⌘K on Apple platforms, Ctrl K elsewhere. apple defaults to the current platform; translations is Kbd's, so { ctrl: \&#x22;Strg\&#x22; } gives Strg K.&#x22;,
  },
  matchHotkey: {
    type: '(hotkey: string, event: KeyboardEvent, apple?: boolean) => boolean',
    description: 'Whether event is hotkey, by the matching rules above.',
  },
}"
/>
