JAVASCRIPT

Capture Keyboard Key Presses with useKey Hook

Develop a `useKey` React hook to detect when a specific keyboard key is pressed, enabling custom keyboard shortcuts or interaction patterns within your application.

import { useEffect, useState } from 'react';

const useKey = (targetKey) => {
  const [keyPressed, setKeyPressed] = useState(false);

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

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

  useEffect(() => {
    window.addEventListener('keydown', downHandler);
    window.addEventListener('keyup', upHandler);

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

  return keyPressed;
};

export default useKey;
How it works: The `useKey` hook tracks the pressed state of a specified `targetKey`. It uses `useEffect` to attach global `keydown` and `keyup` event listeners to the window, updating its internal state `keyPressed` when the target key is detected. This is highly useful for implementing keyboard shortcuts, accessibility features, or handling specific key-driven interactions like closing modals with the 'Escape' key.

Need help integrating this into your project?

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

Hire DigitalCodeLabs