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

🎹 Piano Keyboard

Press keys A S D F G H J K to play notes. Click or use keyboard!

Interactive Piano
React Hooks TS
Recent Notes
Press a key to start...
White keys: A S D F G H J K  • Black keys: W E T Y U

API Reference

function useKeyPress(targetKey: string | string[]): {
  pressed: boolean,
  held: boolean
}

Parameters

NameTypeDescription
targetKeystring | string[]The key(s) to listen for (e.g., 'Enter', ['a', 'b']).

Returns

NameTypeDescription
pressedbooleantrue while the key is being pressed.
heldbooleantrue 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.