本页还没有译文
本页 18 段还没译成Русский,下面显示的是英文原文。useHotkey
还没翻译译自英文(tanstack.com)本页 18 段都还没译
function useHotkey(
hotkey,
callback,
options?): void;Defined in: useHotkey.ts:85
React hook for registering a keyboard hotkey.
Uses the singleton HotkeyManager for efficient event handling. The callback receives both the keyboard event and a context object containing the hotkey string and parsed hotkey.
This hook syncs the callback and options on every render to avoid stale closures. This means callbacks that reference React state will always have access to the latest values.
Parameters
hotkey
RegisterableHotkey
The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object (supports mod for cross-platform)
callback
HotkeyCallback
The function to call when the hotkey is pressed
options?
UseHotkeyOptions = {}
Options for the hotkey behavior. enabled: false keeps the registration (visible in devtools)
and only suppresses firing; the hook updates the existing handle instead of unregistering.
Returns
void
Examples
function SaveButton() {
const [count, setCount] = useState(0)
// Callback always has access to latest count value
useHotkey('Mod+S', (event, { hotkey }) => {
console.log(`Save triggered, count is ${count}`)
handleSave()
})
return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>
}function Modal({ isOpen, onClose }) {
// enabled option is synced on every render
useHotkey('Escape', () => {
onClose()
}, { enabled: isOpen })
if (!isOpen) return null
return <div className="modal">...</div>
}function Editor() {
const editorRef = useRef<HTMLDivElement>(null)
// Scoped to a specific element
useHotkey('Mod+S', () => {
save()
}, { target: editorRef })
return <div ref={editorRef}>...</div>
}