react-hotkeys-hook

raw JSON →
5.3.0 verified Fri May 01 auth: no javascript

A React hook for declaratively handling keyboard shortcuts in components. Current stable version is 5.3.0, released with monthly cadence. It ships TypeScript definitions, supports scopes to prevent hotkey collisions, focus traps, and enables/disables scopes via context. Unlike alternatives like react-hotkeys (maintenance mode) or mousetrap (no React hook), this library is React-first with a simple hook API. Requires React >= 16.8.0. Bundle size is minimal (~2KB gzipped). ESM and CJS exports available.

error TypeError: Cannot read properties of undefined (reading 'enabledScopes')
cause Using v5 code with v4 API (enabledScopes renamed).
fix
Rename 'enabledScopes' to 'activeScopes' in HotkeysProvider.
error Uncaught Error: useHotkeysContext must be used within a HotkeysProvider
cause Using useHotkeysContext but component tree lacks <HotkeysProvider>.
fix
Wrap your app with <HotkeysProvider> or avoid using context outside it.
error Warning: React has detected a change in the order of Hooks called by ExampleComponent
cause Conditional call of useHotkeys inside a component.
fix
Always call useHotkeys unconditionally; use scopes or enabled option for conditional behavior.
error Hotkey 'mod+k' not triggering on macOS
cause v5 uses key code 'KeyK' but 'mod' may still work; however, 'mod' is not a valid key.
fix
Use 'Meta+k' for Cmd key, or 'Control+k' for Ctrl. 'mod' is an alias but not documented.
breaking v5.0.0: Renamed enabledScopes to activeScopes in HotkeysProvider. Also now listens to key code instead of key, which may break custom key mappings.
fix Rename enabledScopes prop to activeScopes. For custom key mappings, use key codes (e.g., 'KeyK' instead of 'k').
breaking v5.0.0: Delimiter changed from custom to always '+'. Previously custom delimiters were allowed.
fix Use '+' exclusively to combine keys. For chord sequences, use array syntax.
deprecated v4.x: Options object keyOrder is deprecated; use orderByKeys or custom sort.
fix Update options to use new property names as per v5 migration guide.
gotcha useHotkeys callback will not fire if the component is not focused unless global option is true.
fix Pass { enabled: true } or { scopes: ['global'] } to listen globally.
gotcha The dependency array in useHotkeys must be explicitly passed for reactivity; otherwise stale closures may occur.
fix Pass deps array as third argument or use functional state updates.
npm install react-hotkeys-hook
yarn add react-hotkeys-hook
pnpm add react-hotkeys-hook

Basic example using useHotkeys with a scope dependency array. Shows increment on Ctrl+K press.

import React, { useState } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';

const Example = () => {
  const [count, setCount] = useState(0);
  useHotkeys('ctrl+k', () => setCount(c => c + 1), { scopes: ['global'] }, [count]);
  return <p>Pressed {count} times.</p>;
};

export default Example;