JAVASCRIPT

React `useKeyPress` Hook for Keyboard Shortcuts

A custom React hook to detect if a specific keyboard key is currently pressed, enabling easy implementation of keyboard shortcuts or game controls in components.

import { useState, useEffect } from 'react';

const 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]);

  return keyPressed;
};

export default useKeyPress;

/* Example Usage:
import React from 'react';

function MyComponent() {
  const happyPress = useKeyPress('h');
  const sadPress = useKeyPress('s');

  return (
    <div>
      {happyPress && '😊'}
      {sadPress && '😢'}
      <p>Press 'h' for happy, 's' for sad.</p>
    </div>
  );
}
*/
How it works: This hook monitors `keydown` and `keyup` events on the window. It maintains a boolean state `keyPressed` which becomes true when the `targetKey` is pressed and false when released. This is useful for implementing custom keyboard shortcuts or responsive UI based on key presses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs