Skip to main content

useShortcuts

useShortcuts is a hook that binds keyboard shortcuts to callbacks, such as opening search with Cmd+K or closing a panel with Escape.

Import

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

Allied components

Other links

Focus the button, then press Up or Down. Count: 0
↑
"use client";

import { Button, Shortcut, Stack, Text, useShortcuts } from "@vortexlabs/vortex";
import React from "react";

export const UseShortcutsExample = () => {
  const [count, setCount] = React.useState(0);
  const { ref, checkShortcutState } = useShortcuts<HTMLDivElement>(
    {
      ArrowUp: () => setCount((value) => value + 1),
      ArrowDown: () => setCount((value) => value - 1),
    },
    [],
    { preventDefault: true },
  );

  return (
    <div ref={ref}>
      <Stack gap={3} align="start">
        <Button variant="secondary" onClick={() => setCount(0)}>Reset count</Button>
        <Text>Focus the button, then press Up or Down. Count: {count}</Text>
        <Shortcut active={checkShortcutState("ArrowUp")}>↑</Shortcut>
      </Stack>
    </div>
  );
};

Features

  • Binds key combinations to callbacks.
  • Scopes callbacks to an element with a ref.
  • Reports which keys are held with checkShortcutState.

Use inside VortexProvider. Pass a shortcut map, optional dependencies, and optional settings. Include values read by callbacks in deps so they stay current.

Attach the returned ref, or pass options.ref, to limit callbacks to keyboard events from that element and its descendants. Without an attached ref, callbacks run globally, including in text fields. Set disabled: true to stop callbacks.

Key Syntax

Join keys with +; matching ignores case. Mod matches Cmd or Ctrl for callbacks. Separate combinations with commas to share a callback.

useShortcuts({
  "Mod+s": handleSave,
  "Mod+Shift+z": handleRedo,
  "ArrowUp, ArrowDown": handleNavigation,
  Escape: handleClose,
});

Set preventDefault: true to prevent the browser's default action when a callback fires. Provide a visible control for each shortcut action.

Held Keys

checkShortcutState reads global key state, even with a scoped ref. Pass null to track keys without a callback.

const { checkShortcutState } = useShortcuts({ "Shift+a": null });
const active = checkShortcutState("Shift+a");

Use actual key names here: Meta+k or Control+k. The Mod alias and comma-separated alternatives only work in callback bindings.