Skip to content

useKeyPress

A hook for detecting keyboard key presses, including support for modifier keys (Ctrl, Alt, Shift). Perfect for implementing keyboard shortcuts and controls.

Parameters

  • config: KeyConfig - Configuration object for the key press detection
    • key: string - The target key to detect
    • ctrl?: boolean - Whether Ctrl key should be pressed
    • alt?: boolean - Whether Alt key should be pressed
    • shift?: boolean - Whether Shift key should be pressed

Returns

  • boolean - Whether the configured key combination is currently pressed

Usage

import { useKeyPress } from '@rhinolabs/react-hooks';
function ShortcutHandler() {
// Detect when 'S' is pressed with Ctrl
const isSavePressed = useKeyPress({ key: 's', ctrl: true });
// Detect when Escape key is pressed
const isEscPressed = useKeyPress({ key: 'Escape' });
return (
<div>
<p>Press Ctrl + S to save</p>
{isSavePressed && <span>Saving...</span>}
<p>Press Escape to cancel</p>
{isEscPressed && <span>Cancelling...</span>}
</div>
);
}

Notes

  • Supports single keys and modifier combinations
  • Automatically handles keydown and keyup events
  • Cleans up event listeners on unmount
  • Works with any keyboard key
  • Handles modifier keys independently
  • Safe for concurrent key presses
  • Updates state in real-time