use-hotkeys-ts
v1.1.4
Published
A typed React hook for handling hotkeys with TypeScript support.
Maintainers
Readme
use-hotkeys-ts
A fully typed React hook for handling keyboard shortcuts and hotkeys with ease.
Key Sequences
You can now use key sequences - combinations of keys pressed one after another:
// Detecting "g" followed by "h"
useHotkeys('g h', () => {
console.log('Redirecting to home page');
});
// With custom delay (default is 1000ms)
useHotkeys('g i t', () => {
console.log('Git command');
}, 2000); // 2 second timeoutImproved Function Key Support
Function keys are now fully supported with better case handling:
useHotkeys('shift+f12', () => {
console.log('Open developer tools');
});Installation
npm install use-hotkeys-tsor
yarn add use-hotkeys-tsQuick Start
import { useHotkeys } from 'use-hotkeys-ts';
useHotkeys('ctrl+s', (e) => {
e.preventDefault();
console.log('Saving...');
});Usage Examples
Multiple Key Combinations
Use an array to match several shortcuts. On macOS, cmd and meta are equivalent (e.g. cmd+s matches ⌘+S):
useHotkeys(['ctrl+s', 'cmd+s'], (e) => {
e.preventDefault();
console.log('Save triggered');
});Special and Function Keys
useHotkeys('f5', () => {
console.log('Page refresh');
});
useHotkeys('/', () => {
console.log('Focus search');
});Integration with react-hook-form
const { handleSubmit } = useForm();
useHotkeys('ctrl+enter', () => {
handleSubmit(onSubmit)();
});Callback return value
Return false from the callback to call event.preventDefault():
useHotkeys('ctrl+s', (e) => {
console.log('Saving...');
return false; // prevents default browser save
});API
useHotkeys(keys, callback, delay?)keys:string | string[]— key combo(s), e.g.'ctrl+s',['ctrl+s', 'cmd+s'], or a sequence like'g h'.callback:(e: KeyboardEvent) => void | boolean— called when the shortcut matches. Returnfalseto calle.preventDefault().delay:number(optional, default1000) — timeout in ms for key sequences (e.g.'g i').
Hotkeys are ignored when focus is inside <input>, <textarea>, <select>, or contenteditable (except types like button, submit, checkbox, radio).
Features
✅ Multiple key combinations
✅ Key sequences (e.g. g i then t)
✅ Full TypeScript support
✅ macOS / Windows: cmd and meta both work
✅ Ignores form elements and contenteditable
✅ Easy integration with forms and UI frameworks
Future Plans
Options: keydown/keyup, ignoreModifiers
Scope restriction via ref (limit hotkey to a DOM node)
Auto-detection of platform (ctrl vs cmd)
Global mode for background hotkeys
Dev/debug mode
Logging and telemetry support
Storybook demo support
