useKeyPress()
useKeyPress(
targetKey,debounce?):boolean
Defined in: hooks/dom/useKeyPress.ts:56
A React hook that tracks whether a specific keyboard key is currently pressed.
This is useful for:
- Implementing keyboard shortcuts (e.g.
Escapeto close a modal). - Responding to navigation keys (e.g.
ArrowUp,ArrowDown). - Showing UI hints based on key state (e.g.
Shift/Ctrlbeing held).
Internally, it:
- Listens to global
keydownandkeyupevents onwindow. - Compares
event.keywith the providedtargetKey(case-sensitive). - Sets
trueonkeydownandfalseonkeyupfor the matching key. - Optionally debounces the updates via useEventListener.
Parameters
targetKey
string
The key to detect (e.g. 'Enter', 'Escape', 'a', 'ArrowUp'). Comparison is done against KeyboardEvent.key, so it is case-sensitive.
debounce?
number = 0
Debounce delay in milliseconds for the underlying event listener.
0(default) means the state updates immediately on key events.- A positive value (e.g.
200) delays state updates until the user stops triggering key events for at least that long.
Returns
boolean
true if the target key is currently pressed, false otherwise.
Examples
// Detect when the Enter key is pressed
tsx
const MyComponent = () => {
const isEnterPressed = useKeyPress('Enter');
return (
<p>Press Enter: {isEnterPressed ? 'Yes' : 'No'}</p>
);
};// Detect Escape with a small debounce
tsx
const MyComponent = () => {
const isEscapePressed = useKeyPress('Escape', 150);
return (
<p>Escape pressed: {isEscapePressed ? 'Yes' : 'No'}</p>
);
};