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.
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.
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)
true only while the key is held. Pressing it sets true; releasing it sets false. A keydown-only listener gets stuck at true forever.window. Attach the listeners to window so the key state is tracked regardless of which element has focus.event.key exactly. Compare against event.key, case-sensitive. 'a' and 'A' (Shift held) are distinct, as are 'Enter' and 'Escape'.targetKey must not change the result.targetKey changes — otherwise listeners leak or track the wrong key.