Skip to content

useShortcut

Runs a callback on a keyboard shortcut and formats the shortcut for the person's platform.

Installation

  1. Add the registryOnce per project
  2. Add use-shortcut

Usage

A shortcut is a TanStack Hotkeys (opens in a new tab) chord, such as Mod+K or Mod+Shift+P, where Mod is ⌘ on a Mac and Ctrl elsewhere. useShortcut runs a callback when the chord is pressed. It's TanStack Hotkeys' useHotkey (opens in a new tab), renamed to match useShortcutDisplay, so its options are documented there. They include target, to listen inside one element, and enabled.

useShortcutDisplay formats a chord for the person's platform in two forms: keys, one label per key for a Kbd Group, and label, all the keys in one string for a single Kbd. For example, ⌘K on a Mac and Ctrl+K elsewhere. The server can't detect the platform, so both stay empty until the page hydrates. The example shows no keys until then rather than guessing and correcting itself. Command uses both hooks to display and bind its items' shortcuts.

API

useShortcut

useShortcut(shortcut, callback, options?) is TanStack Hotkeys' useHotkey.

useShortcutDisplay

useShortcutDisplay(shortcut) takes a chord and returns its keys, which stay empty until the page hydrates:

The file also exports ShortcutChord, the type of a chord.