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.
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> ) }
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.
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> ); }
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"