VayuUI

useKeyPress

A hook that listens for specific key presses and executes a callback.

The useKeyPress hook allows you to trigger a function when a specific key is pressed. This is useful for building keyboard shortcuts, game controls, or accessibility features.

Demo

Press the corresponding keys on your keyboard

A
S
D
F

Source Code

Copy this code into src/hooks/useKeyPress.ts:

import { useEffect } from 'react';

export const useKeyPress = (targetKey: KeyboardEvent['key'], callback: () => void) => {
  useEffect(() => {
    const keyHandler = (event: KeyboardEvent) => {
      if (event.key === targetKey) {
        callback();
      }
    };

    window.addEventListener('keydown', keyHandler);

    return () => {
      window.removeEventListener('keydown', keyHandler);
    };
  }, [targetKey, callback]);
};

Usage

import { useState } from 'react';
import { useKeyPress } from '@/hooks/useKeyPress';

const KeyPressComponent = () => {
  const [count, setCount] = useState(0);

  // Increment count when 'Enter' is pressed
  useKeyPress('Enter', () => {
    setCount((c) => c + 1);
  });

  return (
    <div>
      <p>Press "Enter" to increment count: {count}</p>
    </div>
  );
};

API Reference

Parameters

NameTypeDescription
targetKeystringThe key value to listen for (e.g., "Enter", "Escape", "a").
callback() => voidThe function to be executed when the key is pressed.

On this page