Detect when a specific key is pressed or held. Useful for shortcuts and accessibility.
import { useState, useEffect } from 'react';
export function useKeyPress(targetKey: string): boolean {
const [pressed, setPressed] = useState(false);
useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === targetKey) setPressed(true);
};
const up = (e: KeyboardEvent) => {
if (e.key === targetKey) setPressed(false);
};
window.addEventListener('keydown', down);
window.addEventListener('keyup', up);
return () => {
window.removeEventListener('keydown', down);
window.removeEventListener('keyup', up);
};
}, [targetKey]);
return pressed;
}Pass the key string (e.g. 'Escape', 'Enter', 'a'). Returns true while the key is held down.
Close modal on Escape or trigger action on Enter.
const escapePressed = useKeyPress('Escape'); useEffect(() => { if (escapePressed) onClose(); }, [escapePressed, onClose]);