useKeyCombo
A React hook for handling keyboard shortcuts and key combinations with a simple callback-based API. Perfect for implementing application-wide shortcuts, command palettes, and keyboard navigation.
Interactive Demo
Try these keyboard combinations:
- Ctrl + S
- Ctrl + K
- Shift + ?
Last triggered combo: None
Times triggered: 0
Implementation
type KeyCombo = string[];
type KeyComboCallback = () => void;
export function useKeyCombo(combo: KeyCombo, callback: KeyComboCallback) {
const pressedKeys = useRef(new Set<string>());
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
pressedKeys.current.add(event.key);
// Check if all keys in the combo are pressed
const isComboPressed = combo.every((key) => pressedKeys.current.has(key));
if (isComboPressed) {
event.preventDefault();
callback();
}
};
const handleKeyUp = (event: KeyboardEvent) => {
pressedKeys.current.delete(event.key);
};
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
pressedKeys.current.clear();
};
}, [combo, callback]);
}
Usage Examples
import { useKeyCombo } from '@/components/hooks/useKeyCombo';
function ShortcutsExample() {
// Save shortcut (Ctrl + S)
useKeyCombo(["Control", "s"], () => {
console.log("Save action triggered!");
});
// Open command palette (Ctrl + K)
useKeyCombo(["Control", "k"], () => {
console.log("Command palette opened!");
});
return <div>Press Ctrl + S to save or Ctrl + K to open command palette</div>;
}
Documentation
Key Features
- Support for multiple key combinations
- Callback-based API for easy integration
- Prevents default browser shortcuts when needed
- TypeScript support with proper typing
- Automatic cleanup of event listeners
- Memory efficient implementation
Common Use Cases
- Application shortcuts (Save, Undo, Redo)
- Command palette triggers
- Modal or dialog keyboard controls
- Custom keyboard navigation
- Gaming controls with multiple keys
API Reference
useKeyCombo(combo: string[], callback: () => void): void
Sets up a keyboard combination listener that triggers the callback when all specified keys are pressed.
Parameters:
- combo: Array of keys that make up the combination
- callback: Function to execute when the combination is pressed
Browser Compatibility
The hook uses the standard KeyboardEvent API, which is supported in all modern browsers. Key values follow the KeyboardEvent.key standard. For special keys, refer to theMDN Key Values documentation.