JAVASCRIPT

Detect Specific Key Presses with a Custom useKeyPress Hook

Create a custom React hook, useKeyPress, to easily detect and react to specific keyboard key presses across your components for interactive user experiences.

import React, { useState, useEffect } from 'react';

function useKeyPress(targetKey) {
  const [keyPressed, setKeyPressed] = useState(false);

  useEffect(() => {
    const downHandler = ({ key }) => {
      if (key === targetKey) {
        setKeyPressed(true);
      }
    };

    const upHandler = ({ key }) => {
      if (key === targetKey) {
        setKeyPressed(false);
      }
    };

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

    return () => {
      window.removeEventListener('keydown', downHandler);
      window.removeEventListener('keyup', upHandler);
    };
  }, [targetKey]); // Rerun effect if targetKey changes

  return keyPressed;
}

function KeyPressDetector() {
  const isSpacePressed = useKeyPress(' ');
  const isEnterPressed = useKeyPress('Enter');

  return (
    <div>
      <h1>Press Keys:</h1>
      <p>Space key is pressed: {isSpacePressed ? 'Yes' : 'No'}</p>
      <p>Enter key is pressed: {isEnterPressed ? 'Yes' : 'No'}</p>
      <p>Try pressing and holding the spacebar or enter key.</p>
    </div>
  );
}

export default KeyPressDetector;
How it works: This custom `useKeyPress` hook allows any component to easily detect whether a specific keyboard key is currently being pressed. It utilizes `useEffect` to attach and clean up `keydown` and `keyup` event listeners to the `window` object. When the `targetKey` is pressed down, the `keyPressed` state becomes `true`, and it reverts to `false` when released. This provides a clean, reusable way to build 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