useKeyPressLoading saved progress…

useKeyPress

Build a hook that reports whether a particular keyboard key is currently held down. Plenty of UI reacts to a key being down, not just tapped: showing a hint while the user holds Shift, panning a canvas while Space is pressed, highlighting a shortcut while a modifier is active. useKeyPress(targetKey) returns a boolean that is true from the moment targetKey is pressed until it is released, and false the rest of the time.

The key you track is compared against the event.key value of keyboard events — so 'a', 'Enter', 'Escape', and ' ' (space) are all valid targets. Matching is exact and case-sensitive: 'a' and 'A' are different keys.

Signature

function useKeyPress(targetKey: string): boolean;

It takes the event.key string to track and returns whether that key is down right now. It returns false on the first render, before any key is pressed.

Examples

function ShiftHint() {
  const shiftHeld = useKeyPress('Shift');
  return <p>{shiftHeld ? 'Release Shift to continue' : 'Hold Shift for options'}</p>;
}
// Tracking the letter 'a':
// before any key:        false
// keydown { key: 'a' }   -> true
// keyup   { key: 'a' }   -> false
// keydown { key: 'b' }   -> false  (different key, ignored)

Notes

  • Down means down. The value is true only while the key is held. Pressing it sets true; releasing it sets false. A keydown-only listener gets stuck at true forever.
  • Listen on window. Attach the listeners to window so the key state is tracked regardless of which element has focus.
  • Match event.key exactly. Compare against event.key, case-sensitive. 'a' and 'A' (Shift held) are distinct, as are 'Enter' and 'Escape'.
  • Other keys are ignored. A keydown or keyup for any key other than targetKey must not change the result.
  • Clean up. Remove both listeners when the component unmounts, and re-subscribe when targetKey changes — otherwise listeners leak or track the wrong key.
Loading editor…