useKeyPress
A React hook that detects when specific keyboard keys are pressed or held.
Overview
useKeyPress detects keyboard input for specific keys, returning both momentary press and sustained hold states. Perfect for keyboard shortcuts, game controls, accessibility features, and interactive experiences.
Demo
API Reference
function useKeyPress(targetKey: string | string[]): {
pressed: boolean,
held: boolean
}Parameters
| Name | Type | Description |
|---|---|---|
targetKey | string | string[] | The key(s) to listen for (e.g., 'Enter', ['a', 'b']). |
Returns
| Name | Type | Description |
|---|---|---|
pressed | boolean | true while the key is being pressed. |
held | boolean | true while the key is being held down. |
Usage Examples
Keyboard Shortcut
import { useKeyPress } from 'react-hooks-ts'
function SaveButton() {
const { pressed } = useKeyPress('s')
const cmdKey = useKeyPress('Meta')
useEffect(() => {
if (cmdKey.held && pressed) {
handleSave()
}
}, [pressed, cmdKey.held])
return <button>Save (⌘S)</button>
}Game Controls
import { useKeyPress } from 'react-hooks-ts'
function GameCharacter() {
const left = useKeyPress('ArrowLeft')
const right = useKeyPress('ArrowRight')
return (
<div style={{
transform: `translateX(${right.held ? 10 : left.held ? -10 : 0}px)`
}}>
🏃
</div>
)
}Features
- ⌨️ Multi-Key Support - Listen for single keys or arrays of keys.
- ⚡ Instant Response - Detects both keydown and keyup events.
- 🎮 Hold Detection - Distinguish between taps and sustained presses.
- 🛡️ SSR Safe - Works gracefully with server-side rendering.