useKeyPress

A React hook that tracks keyboard key states. Provides real-time feedback for key press events, perfect for implementing keyboard shortcuts, game controls, or accessibility features. Supports any keyboard key with TypeScript type safety.

Interactive Demo

Key
Space
Key
Enter
Key
Escape
Key
Control
Key
Shift

Recently Pressed Keys

Mini Game: Press the correct keys

Implementation

export function useKeyPress(targetKey: string) {
  const [isKeyPressed, setIsKeyPressed] = useState(false);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === targetKey) {
        setIsKeyPressed(true);
      }
    };

    const handleKeyUp = (event: KeyboardEvent) => {
      if (event.key === targetKey) {
        setIsKeyPressed(false);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  }, [targetKey]);

  return isKeyPressed;
}

Usage Examples

import { useKeyPress } from '@/components/hooks/useKeyPress';

function ShortcutExample() {
  const isCtrlPressed = useKeyPress('Control');
  const isSPressed = useKeyPress('s');
  
  // Save shortcut (Ctrl + S)
  useEffect(() => {
    if (isCtrlPressed && isSPressed) {
      // Prevent default browser save
      event.preventDefault();
      console.log('Save shortcut triggered!');
    }
  }, [isCtrlPressed, isSPressed]);

  return (
    <div>
      <div>Control pressed: {isCtrlPressed ? '✅' : '❌'}</div>
      <div>S pressed: {isSPressed ? '✅' : '❌'}</div>
    </div>
  );
}

Documentation

Key Features

  • Real-time keyboard event tracking
  • Support for all keyboard keys including modifiers (Shift, Ctrl, Alt, etc.)
  • TypeScript support with proper event typing
  • Automatic cleanup of event listeners
  • Memory efficient with single event listener pattern
  • SSR compatible

Common Use Cases

  • Keyboard shortcuts and hotkeys
  • Gaming controls
  • Accessibility features
  • Modal or dialog escape key handling
  • Form submission shortcuts

API Reference

useKeyPress(targetKey: string): boolean

Returns whether the specified key is currently pressed.

Parameters:

  • targetKey: The key to monitor (e.g., "a", "Enter", "Escape", "Control")

Browser Compatibility

The hook uses the standard KeyboardEvent API, which is supported in all modern browsers. Key values follow the KeyboardEvent.key standard. For special keys, refer to theMDN Key Values documentation.