← Back to all snippets
JAVASCRIPT

Detect Key Presses Globally with the `useKeyPress` React Hook

Create a `useKeyPress` hook to easily monitor the state of specific keyboard keys (pressed or not) across your React application for interactive UIs.

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

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]); // Effect is re-run if targetKey changes

  return keyPressed;
}

// Example Usage:
function MyComponent() {
  const isSpacePressed = useKeyPress(' ');
  const isEscapePressed = useKeyPress('Escape');

  return (
    <div>
      <p>Press 'Space': {isSpacePressed ? 'YES' : 'NO'}</p>
      <p>Press 'Escape': {isEscapePressed ? 'YES' : 'NO'}</p>
    </div>
  );
}
How it works: The `useKeyPress` hook tracks whether a specific keyboard key is currently being pressed down. It takes a `targetKey` string as an argument and returns a boolean state (`keyPressed`). Internally, it uses `useEffect` to attach global `keydown` and `keyup` event listeners to the `window` object. These listeners update the `keyPressed` state, which is then returned, and are properly cleaned up when the component unmounts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs