useKeyboardShortcut
Declare and manage keyboard shortcuts effortlessly.
System Interaction
Shortcut Trainer
Master your application speed with custom hotkeys.
Ctrl
K
Press ⌘+K to open palette
Action Log⌘+L to clear
→
Usage
import { useKeyboardShortcut } from 'usehooks-ts'
export default function App() {
useKeyboardShortcut('k', () => {
console.log('Cmd+K or Ctrl+K pressed')
}, { metaKey: true }) // metaKey works for Cmd on Mac and Windows key on Win
return <div>Press Cmd+K to see action</div>
}API
useKeyboardShortcut(key, callback, options?)Parameters
| Name | Type | Default | Description |
|---|---|---|---|
key | string | - | The key to listen for (e.g., 'k', 'Escape', 'Enter') |
callback | (event) => void | - | Function to execute when shortcut matches |
options.altKey | boolean | false | Support for Alt/Option key |
options.ctrlKey | boolean | false | Support for Control key |
options.metaKey | boolean | false | Support for Command (Mac) or Windows key |
options.shiftKey | boolean | false | Support for Shift key |
Hook
import { useEffect } from 'react'
export interface ShortcutOptions {
altKey?: boolean
ctrlKey?: boolean
metaKey?: boolean
shiftKey?: boolean
}
export function useKeyboardShortcut(
key: string,
callback: (event: KeyboardEvent) => void,
options: ShortcutOptions = {},
) {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const {
altKey = false,
ctrlKey = false,
metaKey = false,
shiftKey = false
} = options
if (
event.key.toLowerCase() === key.toLowerCase() &&
event.altKey === altKey &&
event.ctrlKey === ctrlKey &&
event.metaKey === metaKey &&
event.shiftKey === shiftKey
) {
event.preventDefault()
callback(event)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [key, callback, options])
}