useKeyPress()
useKeyPress(
targetKey
,debounce
?):boolean
Defined in: src/hooks/dom/useKeyPress.ts:47
A custom React hook to track whether a specific key is pressed. This hook is useful for implementing keyboard shortcuts or detecting specific key actions in your application. The key detection is case-sensitive and supports optional debouncing for optimized performance during rapid key presses.
Parameters
targetKey
string
The key to detect (e.g., 'Enter', 'Escape', 'a'). The key is case-sensitive.
debounce?
number
= 0
The debounce delay in milliseconds for the event listener. Defaults to 0
(no debounce).
Returns
boolean
true
if the target key is currently pressed, false
otherwise.
Examples
Example: Detect when the Enter key is pressed
tsx
import { useKeyPress } from '@zl-asica/react';
const MyComponent = () => {
const isEnterPressed = useKeyPress('Enter');
return (
<div>
<p>Press the Enter key: {isEnterPressed ? 'Yes' : 'No'}</p>
</div>
);
};
Example: Detect when the Escape key is pressed with debounce
tsx
import { useKeyPress } from '@zl-asica/react';
const MyComponent = () => {
const isEscapePressed = useKeyPress('Escape', 200); // Debounced by 200ms
return (
<div>
<p>Press the Escape key: {isEscapePressed ? 'Yes' : 'No'}</p>
</div>
);
};