Rehooks

useKeyPress

Detects the press state of a specified key.

useKeyPress

Installation

npx rehooks-cli@latest add useKeyPress

Usage

Component.tsx
import { useKeyPress } from "~/hooks/useKeyPress";
 
function Component() {
  const altS = useKeyPress({ key: "s", alt: true });
  return <div>{altS ? "Saving document..." : "Type your text here..."}</div>;
}

API

useKeyPress

useKeyPress.ts
function useKeyPress(options: KeyConfig): boolean;

Returns boolean value indicating whether the specified key combination is currently pressed.

Parameters

NameTypeDescription
optionsKeyConfigThe configuration for the key press detection.
options.keystringThe key to listen for.
options.ctrlbooleanWhether the Ctrl key must be pressed. Optional.
options.altbooleanWhether the Alt key must be pressed. Optional.
options.shiftbooleanWhether the Shift key must be pressed. Optional.
options.metabooleanWhether the Meta key must be pressed. Optional.

Returns

NameTypeDescription
keyPressedbooleantrue if the specified key combination is currently pressed, false otherwise. This value is updated whenever the key combination is pressed or released.

On this page