# useHotkey

Calls `handler` when a keyboard shortcut is pressed, e.g. `'Escape'`, `'mod+k'`, `'shift+/'`.

`mod` is Cmd on Apple devices and Ctrl elsewhere. Modifiers must match exactly, so `'k'` does not fire for Ctrl+K. Ignored during IME composition, and while typing in inputs, textareas, selects, and contenteditable, except Escape. Key names follow `KeyboardEvent.key`, case-insensitive; `esc` and `space` work as aliases.

## Import

```ts
import { useHotkey } from '@vincent.ri/react-tils'
// or only this hook
import { useHotkey } from '@vincent.ri/react-tils/useHotkey'
```

## Usage

```ts
useHotkey('mod+k', () => setPaletteOpen(true))
useHotkey('Escape', () => setPaletteOpen(false), { enabled: paletteOpen })
```

## When to use it

Global shortcuts like a command palette (`mod+k`), closing a modal with Escape, or `/` to focus search.

## When not to

The shortcut belongs to one focused element; use its `onKeyDown` prop. For text input handling, use the input's own events.

## API

```ts
function useHotkey(hotkey: string, handler: (event: KeyboardEvent) => void, options?: HotkeyOptions): void
```

| Parameter | Description |
| --- | --- |
| `hotkey` | Modifiers and a key joined by `+`: `ctrl`, `alt`, `shift`, `meta`, `mod`. Separate steps with spaces for a sequence: `'g i'` fires after g then i, each within a second of the previous one. |
| `handler` | Called with the `KeyboardEvent`. Can change every render. |
| `options` | `enabled`, `preventDefault`, `enableInInputs`. All optional. |

### Types

```ts
export type HotkeyOptions = {
  /** Listen only while `true`. Default `true`. */
  enabled?: boolean;
  /** Call `event.preventDefault()` on a match, e.g. to stop the browser's own `ctrl+k`. Default `true`. */
  preventDefault?: boolean;
  /** Also fire while typing in inputs, textareas, selects, and contenteditable. Default `false` (Escape always fires). */
  enableInInputs?: boolean;
};
```

## Browser support

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useKey`, `useKeyPress`, `useHotkeys`.

---

586 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useHotkey.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useHotkey/
Previous: [useClickOutside](https://vincentri.github.io/react-tils/hooks/useClickOutside.md)
Next: [useLongPress](https://vincentri.github.io/react-tils/hooks/useLongPress.md)
