Rehooks
Content

useKeyPress

Custom hook to detect if a specified key is pressed.

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

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.

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