Skip to content
@pyreon/hotkeys
fundamentals · keyboard

You have written this keydown listener before. It was the last time.

useHotkey('mod+s', save) is ⌘S on a Mac and Ctrl+S everywhere else, skips text fields, stops the browser's own save dialog and unregisters when the component goes. Sequences like g i, scopes for the editor, and a list of every shortcut for your help dialog come with it.

bun add @pyreon/hotkeys
Documentation
one line
useHotkey('mod+s', save)⌘ on Mac, Ctrl elsewhere; removed on unmount.
a non-shortcut key
one Map lookupHowever many shortcuts are registered.
vs tinykeys, hotkeys-js, mousetrap
misses 6.0–118× fasterOne run, bun/JavaScriptCore, 12 and 48 bindings.
iOS and Android
useHotkey with a literal shortcutA SwiftUI .keyboardShortcut or a Compose key handler; native is experimental. The registry stays web.
Shortcuts that reach the right handler and nothing else Schematic: pressing ⌘S (Ctrl+S off a Mac) reaches the Save handler registered with useHotkey('mod+s', save) and the browser's own save dialog is prevented. Pressing ⌘Z does nothing while the editor scope is off; once useHotkeyScope('editor') is active, the same keys reach Undo. USEHOTKEY('MOD+S', SAVE) · SCOPES · REMOVED ON UNMOUNT keys ⌘ S Z mod = ⌘ on Mac, Ctrl elsewhere text fields are skipped global 'mod+s'→ save() default prevented scope 'editor' active off 'mod+z'→ undo() ⌘Z, editor scope off:no handler runs useHotkeyScope('editor')the editor mounted useHotkey('mod+z', undo, { scope: 'editor' }) sequences like g i · a list of every shortcut for your help dialog
  • 6–118× faster than tinykeys, hotkeys-js and mousetrap on a key that is not a shortcut (12 and 48 bindings, one run)BENCHMARKS.md §10, hotkeys row: miss 6.0–118× · overnight run, one run, bun/JavaScriptCore
  • 1.7–7.5× faster dispatch when the key is a shortcutBENCHMARKS.md §10, hotkeys row · vs tinykeys, hotkeys-js, mousetrap
  • 1 shared listener per target and event type, for every shortcutpackages/fundamentals/hotkeys/src/manifest.ts; src/types.ts target option

synthetic · author-run · M3 Max · record of 2026-11-05

Every result, including where we lose →
why teams pick it

The details you forget at 11 pm.

  1. Typing is not a shortcut

    Shortcuts stay quiet while focus is in an input, textarea, select or contenteditable. Opt back in with enableOnInputs: true, or only for text inputs with ['input'].

  2. mod means the right key

    ⌘ on macOS, Ctrl on Windows and Linux, from one string. ? fires on Shift+/, so the help shortcut works on every layout that has a question mark.

  3. Scopes that stack

    useHotkeyScope('editor') turns the editor's Ctrl+Z on while the editor is mounted. Activation is reference-counted, so two editors on one page do not switch each other off.

  4. A miss costs one lookup

    Dispatch is bucketed by key. A keypress that is not a shortcut, which is most of them, touches one Map and leaves, however many shortcuts you registered.

the difference

Fifteen lines you keep re-typing.

React, by hand

Skip inputs, guess the platform, prevent the default, remember the cleanup. In every component that needs a shortcut.

useEffect(() => {
  const onKey = (e: KeyboardEvent) => {
    const t = e.target as HTMLElement
    if (t.isContentEditable ||
        /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)) return
    const mod = navigator.platform.includes('Mac')
      ? e.metaKey : e.ctrlKey
    if (mod && e.key.toLowerCase() === 's') {
      e.preventDefault()
      save()
    }
  }
  window.addEventListener('keydown', onKey)
  return () => window.removeEventListener('keydown', onKey)
}, [save])
with @pyreon/hotkeys

Same behaviour. Inputs skipped, default prevented, removed on unmount, listed in your help dialog.

import { useHotkey } from '@pyreon/hotkeys'

useHotkey('mod+s', () => save(), { description: 'Save' })
coming from

Coming from tinykeys or hotkeys-js?

$mod+KeyK becomes mod+k.

tinykeys
import { tinykeys } from 'tinykeys'

useEffect(
  () =>
    tinykeys(window, {
      '$mod+KeyK': (e) => {
        e.preventDefault()
        openPalette()
      },
      'g i': () => goToInbox(),
    }),
  [],
)
Pyreon

Sequences use the same space-separated form. preventDefault is on by default; pass preventDefault: false to let the browser act too.

import { useHotkey } from '@pyreon/hotkeys'

useHotkey('mod+k', () => openPalette())
useHotkey('g i', () => goToInbox())

Scopes without a global setScope.

hotkeys-js
import hotkeys from 'hotkeys-js'

useEffect(() => {
  hotkeys('ctrl+s, command+s', (e) => {
    e.preventDefault()
    save()
  })
  hotkeys('ctrl+z', 'editor', () => undo())
  hotkeys.setScope('editor')
  return () => {
    hotkeys.unbind('ctrl+s, command+s')
    hotkeys.unbind('ctrl+z', 'editor')
  }
}, [])
Pyreon

hotkeys-js has one active scope at a time. Here any number of scopes can be on together, each held for as long as a component that asked for it is mounted.

import { useHotkey, useHotkeyScope } from '@pyreon/hotkeys'

useHotkey('mod+s', () => save())

// in the editor component:
useHotkeyScope('editor')
useHotkey('ctrl+z', () => undo(), { scope: 'editor' })
try it

Press the keys.

Click inside the box to give it focus, then try the shortcuts. Toggle the editor scope to see scoped keys switch on and off.

registered shortcuts
  • Open command palette⌘/Ctrl K
  • Go to inboxG then I
  • Show shortcuts?
  • Save · editor⌘/Ctrl S
  • Undo · editor⌘/Ctrl Z
  • CloseEsc

Click here, then press a shortcut.

const box = () => boxEl   // keys fire only while focus is inside it
useHotkey('mod+k', openPalette, { target: box })
useHotkey('g i', goToInbox, { target: box })
useHotkey('?', showHelp, { target: box })
useHotkey('escape', close, { target: box })
useHotkey('mod+s', save, { target: box, scope: 'editor' })
useHotkey('mod+z', undo, { target: box, scope: 'editor' })

// while the toggle is on:
useHotkeyScope('editor')
  • shortcuts fired0
  • active scopesglobal

Shortcuts are ignored while typing in a field, and a held key's auto-repeat can be skipped with ignoreRepeat.

benchmarks

A key that is not a shortcut: up to 118× cheaper.

Most keypresses are typing, not shortcuts, so the miss path is the one that runs all day. Pyreon buckets shortcuts by key; a miss is one lookup. Ranges cover the three rivals and both binding counts. No loss or tie is recorded.

vs tinykeys 4, hotkeys-js 4, mousetrap 1.6 · bun/JavaScriptCore, 12 and 48 bindingsPyreonrival · lower is better
  • dispatch, key is not a shortcut
    win6.0–118×
  • dispatch, key is a shortcut
    win1.7–7.5×
  • register + teardown vs tinykeys
    win1.17×
  • register + teardown vs hotkeys-js, mousetrap
    win9–14×
Apple M3 Max · record of 2026-11-05 · overnight run, one run · author-run, syntheticFull method, every loss →
what's included

Every shortcut pattern, one registry.

  • useHotkey Registers on setup, unregisters on unmount. target takes an element ref for panel-local keys.
  • Sequences g i, Gmail and vim style: the next key must follow within a second.
  • Comma lists 'ctrl+s, mod+p' binds one handler to several combos.
  • useHotkeyScope Reference-counted scopes; enableScope / disableScope for code outside components.
  • event: 'keyup' Act on release, for push-to-talk.
  • once and ignoreRepeat Fire once and unregister, or ignore auto-repeat while a key is held.
  • enabled: () => … Gate a shortcut on a signal: no re-registering when the condition flips.
  • trigger('g i') Run the bound action from a command palette or a test. Returns how many handlers fired.
  • getRegisteredHotkeys() Every shortcut with its scope and description, ready for a "?" help dialog.
  • getHotkeyConflicts() Finds ctrl+s and control+s bound twice in one scope, even when the strings differ.
recipes

Things to build with it.

A help dialog that lists itself

Give each shortcut a description. The list that ? opens reads the registry each time it opens, so it never drifts from what is bound.

import { For, Show } from '@pyreon/core'
import { signal } from '@pyreon/reactivity'
import { formatCombo, getRegisteredHotkeys, parseShortcut, useHotkey } from '@pyreon/hotkeys'

// 'g i' is a sequence: format each step
const label = (shortcut: string) =>
  shortcut.split(/\s+/).map((step) => formatCombo(parseShortcut(step))).join(' then ')

export function Shortcuts(props: { openPalette: () => void; goToInbox: () => void }) {
  const open = signal(false)
  useHotkey('mod+k', props.openPalette, { description: 'Command palette' })
  useHotkey('g i', props.goToInbox, { description: 'Go to inbox' })
  useHotkey('?', () => open.set(true), { description: 'Show shortcuts' })
  useHotkey('escape', () => open.set(false), { description: 'Close this list' })

  // getRegisteredHotkeys() is a snapshot: read it each time the list opens
  return (
    <Show when={open()}>
      {() => (
        <dl>
          <For each={[...getRegisteredHotkeys()]} by={(h) => h.shortcut}>
            {(h) => (
              <>
                <dt>{label(h.shortcut)}</dt>
                <dd>{h.description}</dd>
              </>
            )}
          </For>
        </dl>
      )}
    </Show>
  )
}
Shortcuts that only work in the panel

Escape closes the panel only while focus is inside it. The listener is shared and removed with the last binding.

import { elementRef, type VNodeChild } from '@pyreon/core'
import { useHotkey } from '@pyreon/hotkeys'

const Panel = (props: { onClose: () => void; children?: VNodeChild }) => {
  const panel = elementRef<HTMLDivElement>()
  useHotkey('escape', () => props.onClose(), { target: panel })
  return <div ref={panel} tabIndex={-1}>{props.children}</div>
}
api

Hooks, a registry and a parser.

Every export has a reference page with its signature, an example and the mistakes people make with it.

hooks · 2
  • useHotkey
  • useHotkeyScope
registry · 9
  • registerHotkey
  • trigger
  • enableScope
  • disableScope
  • getActiveScopes
  • getRegisteredHotkeys
  • getHotkeyConflicts
  • getPressedKeys
  • isKeyPressed
parsing · 4
  • parseShortcut
  • formatCombo
  • matchesCombo
  • splitShortcutList
types · 5
  • UseHotkeyOptions
  • HotkeyOptions
  • HotkeyEntry
  • KeyCombo
  • InputKind
good to know

Good to know before you start.

Text fields win by default

A shortcut does not fire while the user types. If ⌘S should save from inside a textarea, pass enableOnInputs: ['textarea'] or true.

Build server help panels from config

Registration is a no-op on the server, so getRegisteredHotkeys() is empty during SSR. Render a static list there, or the live one after mount.

Sequences fire on keydown

g i cannot use event: 'keyup'; registration throws a clear error if you try.

On native, keep it literal

iOS and Android lower useHotkey with a literal shortcut and a handler that does not read the event. A computed shortcut, a comma list or a handler reading e.key warns by name and is dropped there.

questions

What people ask first.

Does it prevent the browser default?

Yes, by default, which is what you want for ⌘S and ⌘K. Pass preventDefault: false for a shortcut that should let the browser act as well.

What about keyboard layouts and IME input?

Matching uses the key the layout produces, so ? fires on Shift+/. With Alt held it falls back to the physical key, so alt+s works on a Mac, where Option+S types ß. Keystrokes inside an IME composition never match, so typing Japanese or Chinese does not trigger shortcuts.

How fast is it?

Against tinykeys, hotkeys-js and mousetrap: dispatch on a hit 1.7–7.5×, a miss 6.0–118× with 12 and 48 bindings, register plus teardown 1.17× vs tinykeys and 9–14× vs the other two. One run, bun, author-run; the record lists no loss.

Do I need to clean up?

Not with useHotkey: it unregisters on unmount. registerHotkey returns an unregister function for code outside components.

Press ? to see what else it does.

bun add @pyreon/hotkeys
Read the hotkeys guide