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
Waiting for shortcut...

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

NameTypeDefaultDescription
keystring-The key to listen for (e.g., 'k', 'Escape', 'Enter')
callback(event) => void-Function to execute when shortcut matches
options.altKeybooleanfalseSupport for Alt/Option key
options.ctrlKeybooleanfalseSupport for Control key
options.metaKeybooleanfalseSupport for Command (Mac) or Windows key
options.shiftKeybooleanfalseSupport 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])
}