Skip to main content

React Hotkeys Hook

Use hotkeys in a declarative way

Declarative

Define your hotkeys declaratively once, and let React Hotkeys take care of all the nitty gritty details of binding and unbinding them.

Batteries included

Memoisation, enable on form fields, check for currently pressed keys. React Hotkeys has you covered.

TypeScript logo

Powered by TypeScript

React Hotkeys Hook is written with TypeScript, so all typings come with it.

Easy to use

Use just one hook to bind your hotkeys to a component.

function MyAwesomeComponent() {
const [count, setCount] = useState(0)
useHotkeys('a', () => setCount(prevCount =>
prevCount + 1
))

return (
<span>{count}</span>
)
}
function MyAwesomeComponent() {
const [count, setCount] = useState(0)
const ref = useHotkeys('b', () => setCount(prevCount =>
prevCount + 1
))

return (
<div>
<span>
Focusing this element will disable the hotkey {count}.
</span>
<br/>
<span ref={ref} tabIndex='-1'>
Focusing this element will enable the hotkey {count}.
</span>
</div>
)
}

Dead simple component scoping

With the usage of a returned ref you can easily scope your callback to your component, sub component or subtree.

Modifier support and combinations

Use all major modifiers. You can also combine multiple hotkey combinations to trigger the same callback. Supports ctrl, cmd, option, alt, pagedown, etc.

function MyAwesomeComponent() {
const [count, setCount] = useState(0);
useHotkeys('ctrl+a, shift+ctrl+x', () => setCount(prevCount =>
prevCount + 1
))

return (
<span>{count}</span>
)
}
function MyAwesomeComponent() {
const [enabled, setEnabled] = useState(false)
const [count, setCount] = useState(0)
useHotkeys('shift+c', () => setCount(prevCount => prevCount + 1), {
enabled,
})

const onClick = () => setEnabled(prevEnabled => !prevEnabled)

return (
<div>
<button onClick={onClick}>Toggle Hotkey</button>
<p>Hotkey is {!enabled && 'not'} enabled.</p>
<p>Pressed the 'shift+c' keystroke {count} times.</p>
</div>
)
}

Dynamically enable or disable hotkeys

You can enable and disable hotkeys during runtime as well as prevent the defaults browser behavior.