@dhruvilshah191999/use-shortcut

中文文档
0.2.3发布于 2026/06/04MITTypeScriptESM + CJS零依赖近 30 天下载 9650

Tiny zero-dependency React hook for keyboard shortcuts. Cross-platform, TypeScript-first.

原始使用文档
文档目录16 节
  1. Install
  2. Usage
  3. Why this hook?
  4. API
  5. useShortcut(key, callback, options?)
  6. Options
  7. Examples
  8. Basic
  9. Cross-platform
  10. Multiple shortcuts for the same action
  11. Modal close on Escape
  12. Prevent default browser behavior
  13. Scopes (optional)
  14. Caveats
  15. When NOT to use this
  16. License

@dhruvilshah191999/use-shortcut

Tiny zero-dependency React hook for keyboard shortcuts. Cross-platform, TypeScript-first, ~1KB gzipped.

npm version bundle size license: MIT

▶ Live demo — try every feature in your browser (source).

Install

npm install @dhruvilshah191999/use-shortcut
pnpm add @dhruvilshah191999/use-shortcut
yarn add @dhruvilshah191999/use-shortcut
bun add @dhruvilshah191999/use-shortcut

Usage

import { useShortcut } from "@dhruvilshah191999/use-shortcut";

useShortcut("mod+k", () => setOpen(true));

Why this hook?

  • Zero dependencies
  • Tiny (~1KB gzipped)
  • Cross-platform out of the box: mod becomes Cmd on Mac, Ctrl elsewhere
  • Smart input field handling: shortcuts don't fire while you're typing (except Escape)
  • TypeScript types built in
  • Always-fresh callback: no stale closures, no useCallback needed

API

useShortcut(key, callback, options?)

ParameterTypeDescription
keystring | string[]A combo like "mod+k", or an array of combos that map to one action.
callback(e: KeyboardEvent) => voidCalled with the matching event. Always the latest reference.
optionsOptionsOptional. See below.

Combo syntax is case-insensitive and whitespace-tolerant: "Cmd+K", "cmd+k", and " cmd + k " are equivalent. Supported modifier aliases: mod, cmd/command, ctrl/control, alt/option, shift, meta.

Options

OptionTypeDefaultDescription
enabledbooleantrueWhether the shortcut is active.
preventDefaultbooleanfalseCall event.preventDefault() on match.
stopPropagationbooleanfalseCall event.stopPropagation() on match.
enableInInputsbooleanfalseFire even while typing in inputs/textarea/select/contenteditable.
targetRefObject<HTMLElement> | WindowwindowWhere to attach the listener. Use a ref to scope a shortcut to one element.
scopestring | string[]—Restrict the shortcut to named scope(s); fires only while one is active. See Scopes.

Examples

Basic

// Cmd+K (Mac) / Ctrl+K (Windows/Linux) to open search
useShortcut("mod+k", () => openSearch());

Cross-platform

// `mod` resolves to Cmd on Mac and Ctrl everywhere else
useShortcut("mod+s", () => save());

Multiple shortcuts for the same action

useShortcut(["mod+k", "/"], () => openSearch());

Modal close on Escape

useShortcut("escape", () => setOpen(false), { enabled: isOpen });

Prevent default browser behavior

// Stop the browser's native "Save page" dialog
useShortcut("mod+s", () => save(), { preventDefault: true });

Scopes (optional)

By default every shortcut is global — it fires whenever its combo matches. If you need the same key to do different things in different parts of the app (list navigation vs. an open modal, say), opt into scopes: tag a shortcut with a scope, wrap the relevant subtree in <ShortcutProvider>, and activate/deactivate scopes with useShortcutScopes().

Shortcuts without a scope stay global and need no provider — scopes are purely additive.

import {
  ShortcutProvider,
  useShortcut,
  useShortcutScopes,
} from "@dhruvilshah191999/use-shortcut";

function App() {
  // `list` is active on first render; `modal` is off until we open the modal
  return (
    <ShortcutProvider initialScopes={["list"]}>
      <List />
      <Modal />
    </ShortcutProvider>
  );
}

function List() {
  // fires only while the "list" scope is active
  useShortcut("j", selectNext, { scope: "list" });
  return /* ... */;
}

function Modal() {
  const { activate, deactivate } = useShortcutScopes();

  function open() {
    activate("modal");   // modal shortcuts start firing
    deactivate("list");  // list shortcuts pause
  }

  // fires only while the "modal" scope is active
  useShortcut("escape", close, { scope: "modal" });
  return /* ... */;
}

useShortcutScopes() returns { activeScopes, activate, deactivate, toggle, set }. A shortcut can belong to several scopes ({ scope: ["a", "b"] }) and fires if any of them is active.

If you use a scope without a <ShortcutProvider>, the shortcut degrades to global behavior and warns once in development.

Caveats

  • No sequence support (e.g., g g).
  • Scopes are opt-in via <ShortcutProvider>; without one, every shortcut is global (you can also narrow a single shortcut to an element with the target option).
  • No priority/conflict resolution — multiple handlers for the same combo all fire. Use scopes to gate which handlers are live.

When NOT to use this

If you need key sequences (e.g., g g), a help-modal generator, or a key-recorder UI, use react-hotkeys-hook or TanStack Hotkeys.

License

MIT

版本与发布记录

@dhruvilshah191999/use-shortcut 共发布 4 个版本,首次发布于 2026/06/01;过去 12 个月发布了 4 个版本。

版本发布日期距今
0.2.3latest2026/06/045 个月前
0.2.22026/06/035 个月前
0.2.12026/06/015 个月前
0.2.02026/06/015 个月前

关于 @dhruvilshah191999/use-shortcut 的常见问题

@dhruvilshah191999/use-shortcut 是什么?

Tiny zero-dependency React hook for keyboard shortcuts. Cross-platform, TypeScript-first.

如何安装 @dhruvilshah191999/use-shortcut?

在项目目录运行 npm install @dhruvilshah191999/use-shortcut,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dhruvilshah191999/use-shortcut 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dhruvilshah191999/use-shortcut 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@dhruvilshah191999/use-shortcut 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dhruvilshah191999/use-shortcut 可以商用吗?

@dhruvilshah191999/use-shortcut 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dhruvilshah191999/use-shortcut 的下载量有多少?

根据 npm 官方下载统计,@dhruvilshah191999/use-shortcut 在 2026/10/12 – 2026/11/10 这 30 天内被下载 9,650 次,日均约 322 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dhruvilshah191999/use-shortcut 还在维护吗?

最新版本 0.2.3 发布于 2026/06/04(5 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/06/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。