Skip to main content

useShortcuts

Hook for binding keyboard shortcuts to callbacks and reading whether specific key combinations are currently pressed.

Features

  • Binds key combinations to callbacks.
  • Cross-platform support.
  • Tracks pressed state with checkShortcutState.
  • Supports disabled and preventDefault options.
  • Scopes shortcuts to a specific element via ref.

Usage

useShortcuts accepts a map of key combinations to callbacks. Mod+ resolves to Cmd on macOS and Ctrl on Windows.

import { useShortcuts } from "@vortexlabs/vortex";

useShortcuts(
{
  "Mod+k": (e) => {
    e?.preventDefault();
    // open command palette
  },
  Escape: () => {
    // close dialog
  },
},
[],
{ preventDefault: true },
);

Shortcut state

checkShortcutState returns true while a key combination is held. It can drive the active prop on Shortcut to reflect real-time key press state.

⌘KShortcut while ⌘K is held
import { useShortcuts, Shortcut } from "@vortexlabs/vortex";

const { checkShortcutState } = useShortcuts({ "Mod+k": null }, []);

<Shortcut active={checkShortcutState("Mod+k")}>⌘K</Shortcut>

Scoped shortcuts

Shortcuts scope to a specific element when ref is provided in options. The callback fires only when focus is inside that element.

import React from "react";
import { useShortcuts } from "@vortexlabs/vortex";

const ref = React.useRef<HTMLDivElement>(null);

useShortcuts(
{ ArrowUp: handleUp, ArrowDown: handleDown },
[],
{ ref },
);

<div ref={ref}>
{/* shortcuts only active when focus is inside here */}
</div>

Key syntax

Key combinations use + as a delimiter and are case-insensitive. Multiple combinations can share a single callback with a comma-separated string.

useShortcuts({
"Mod+s": handleSave,           // Cmd+S / Ctrl+S
"Mod+Shift+z": handleRedo,     // Cmd+Shift+Z / Ctrl+Shift+Z
"ArrowUp, ArrowDown": handleNav, // both keys share one handler
"Escape": handleClose,
});

Accessibility

Shortcuts registered via useShortcuts respond to keydown events at the window level unless scoped via ref.

Description
preventDefault: true prevents browser defaults such as Cmd+S triggering a file save.
Passing null as a callback registers the key for state tracking only, with no side effects on press.