← Back to all snippets
JAVASCRIPT

Detect Keyboard Key Presses with useKeyPress Hook

A convenient React hook to detect when a specific keyboard key is pressed, simplifying the implementation of keyboard shortcuts and interactive controls.

import { useState, useEffect } from 'react';

// A utility hook that can be used or adapted for useEventListener as well
// For this snippet, we'll keep it self-contained for clarity.

function useKeyPress(targetKey) {
  // State for keeping track of whether key is pressed
  const [keyPressed, setKeyPressed] = useState(false);

  // Add event listeners
  useEffect(() => {
    // If pressed key is our target key then set to true
    const downHandler = ({ key }) => {
      if (key === targetKey) {
        setKeyPressed(true);
      }
    };

    // If released key is our target key then set to false
    const upHandler = ({ key }) => {
      if (key === targetKey) {
        setKeyPressed(false);
      }
    };

    window.addEventListener('keydown', downHandler);
    window.addEventListener('keyup', upHandler);

    // Remove event listeners on cleanup
    return () => {
      window.removeEventListener('keydown', downHandler);
      window.removeEventListener('keyup', upHandler);
    };
  }, [targetKey]);

  return keyPressed;
}

export default useKeyPress;

// Example Usage:
// function MyComponent() {
//   const isSpacePressed = useKeyPress(' ');
//   const isEnterPressed = useKeyPress('Enter');

//   return (
//     <div>
//       <p>Spacebar pressed: {isSpacePressed ? 'Yes' : 'No'}</p>
//       <p>Enter key pressed: {isEnterPressed ? 'Yes' : 'No'}</p>
//     </div>
//   );
// }
How it works: The `useKeyPress` hook allows React components to easily detect and react to specific keyboard key presses. It attaches `keydown` and `keyup` event listeners to the `window`, updating its internal state (`keyPressed`) based on whether the `targetKey` is currently being held down. This is ideal for implementing custom keyboard shortcuts, game controls, or other keyboard-driven interactions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs