Skip to main content
Version: 5.0

useRecordHotkeys

useRecordHotkeys lets you capture whatever keys the user presses. This is useful for building custom keyboard shortcut settings — for example, letting users define their own hotkeys.

Basic usage

Import the hook from the package:

import { useRecordHotkeys } from 'react-hotkeys-hook';

Record hotkeys

Call useRecordHotkeys to start capturing keystrokes. It returns a tuple: the first element is a Set of recorded keys, and the second element is a control object with start, stop, resetKeys, and isRecording.

Live Editor
function ExampleComponent() {
  const [keys, { start, stop, isRecording }] = useRecordHotkeys()

  return (
    <div>
      <p>Is recording: {isRecording ? 'yes' : 'no'}</p>
      <p>Recorded keys: {Array.from(keys).join(' + ')}</p>
      <br />
      <button onClick={start}>Record</button>
      <button onClick={stop}>Stop</button>
    </div>
  )
}
Result
Loading...
Recorded keys are a Set

Each key is recorded only once. The returned value is a Set<string> rather than an array, which makes deduplication easy. Convert it to an array when you need to display or store the keys.

Ignoring specific keys

Pass a blacklist array as the second argument to exclude certain keys from being recorded. Blacklisted keys keep their default behavior and are not added to the recorded set.

Live Editor
function ExampleWithBlacklist() {
  const [keys, { start, stop, resetKeys, isRecording }] = useRecordHotkeys(false, ['tab', 'enter']);

  return (
    <div>
      <p>Recording (ignoring Tab and Enter): {isRecording ? 'yes' : 'no'}</p>
      <p>Recorded keys: {Array.from(keys).join(' + ')}</p>
      <button onClick={start}>Record</button>
      <button onClick={stop}>Stop</button>
      <button onClick={resetKeys}>Reset Keys</button>
    </div>
  );
}
Result
Loading...

Recording produced characters vs. key codes

By default, useRecordHotkeys records key codes (physical keys). To record the produced character instead, pass true as the first argument:

const [keys, controls] = useRecordHotkeys(true); // records characters like "!" instead of "shift+1"