Using TypeScript
TypeScript support
React Hotkeys Hook includes TypeScript types. No additional @types package is needed.
Type-safe key names
The keys argument must be a string or array of strings. TypeScript catches incorrect types at compile time:
import { useHotkeys } from 'react-hotkeys-hook'
import { useState } from 'react'
interface Props {
hotKey: number // ❌ wrong type
}
const MyComponent = ({ hotKey }: Props) => {
const [count, setCount] = useState(0)
// TypeScript error: hotKey must be a string
useHotkeys(hotKey, () => setCount((prevCount) => prevCount + 1))
return <div>The count is {count}.</div>
}
Typing the ref
When scoping hotkeys to a specific element, you can type the returned ref for full type safety:
import { useHotkeys } from 'react-hotkeys-hook'
import { useState } from 'react'
interface Props {
hotKey: string
}
const MyComponent = ({ hotKey }: Props) => {
const [count, setCount] = useState(0)
const ref = useHotkeys<HTMLDivElement>(hotKey, () => setCount((prevCount) => prevCount + 1))
return (
<div ref={ref} tabIndex={-1}>
The count is {count}.
</div>
)
}
Typed options
The options object is fully typed, so you get autocomplete and type checking for all configuration properties:
useHotkeys('ctrl+s', handleSave, {
enabled: true,
preventDefault: true,
scopes: ['editor'],
enableOnFormTags: ['input', 'textarea'],
})
Custom metadata
You can attach custom metadata to hotkeys for your own use cases (for example, building a help panel that lists all active shortcuts):
useHotkeys('ctrl+s', handleSave, {
description: 'Save the current document',
metadata: { category: 'file', showInHelp: true },
})