Quick Start
This guide adds keyboard shortcuts to a React app. If you haven't installed TanStack Hotkeys yet, see Installation.
Register a hotkey#
TanStack Hotkeys needs no setup or provider to start. Call useHotkey in the component that owns the action:
import { useHotkey } from '@tanstack/react-hotkeys'
function Editor() {
useHotkey('Mod+S', () => saveDocument())
return <textarea />
}Mod resolves to Command on macOS and Control on Windows and Linux. Out of the box, the browser's Save dialog stays closed, and Mod+S still fires while typing inside the <textarea>. See Sensible Defaults to learn how every default works.
Providers, scopes, and the rest of the features below are completely optional. Add them only as your app needs them.
Register several hotkeys#
When a component needs multiple shortcuts, register them together with useHotkeys:
import { useHotkeys } from '@tanstack/react-hotkeys'
function Editor() {
useHotkeys([
{ hotkey: 'Mod+S', callback: () => save() },
{ hotkey: 'Mod+Z', callback: () => undo() },
{ hotkey: 'Mod+Shift+Z', callback: () => redo() },
])
return <textarea />
}Because useHotkeys takes an array, the list can come from dynamic data and change length between renders, unlike calling useHotkey in a loop.
Sequences#
Pass an array of chords to register a multi-step sequence, pressed one after another:
useHotkey(['G', 'G'], () => scrollToTop())By default, each step must follow the previous one within 1 second. useHotkeys accepts chords and sequences in the same array:
useHotkeys([
{ hotkey: 'Mod+K', callback: () => openSearch() },
{ hotkey: ['G', 'H'], callback: () => goHome() },
{ hotkey: ['G', 'S'], callback: () => goToSettings() },
])Show the shortcut#
Format a shortcut for buttons, menus, or tooltips with useFormatForDisplay. Passing the same binding you register guarantees the label always stays in sync:
import { useFormatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
import type { HotkeyChord } from '@tanstack/react-hotkeys'
const saveHotkey: HotkeyChord = 'Mod+S'
function SaveButton() {
useHotkey(saveHotkey, () => save())
const formatForDisplay = useFormatForDisplay()
return (
<button onClick={save}>
Save <kbd>{formatForDisplay(saveHotkey)}</kbd>
</button>
)
}This renders ⌘ S on macOS and Ctrl+S on Windows and Linux. HotkeyChord type-checks the string so typos fail at compile time. Use Hotkey if a value can also be a sequence.
In server-rendered apps like TanStack Start or Next.js, pass the request's platform to HotkeysProvider so server HTML matches the client without hydration errors. See SSR & Hydration.
Hotkeys follow your components#
Hotkeys register when the calling component mounts and unregister when it unmounts. Put each shortcut in the component it belongs to so it's only active while rendered:
function App() {
const [isOpen, setIsOpen] = useState(false)
return (
<>
<button onClick={() => setIsOpen(true)}>Settings</button>
{isOpen && <SettingsDialog onClose={() => setIsOpen(false)} />}
</>
)
}
function SettingsDialog({ onClose }: { onClose: () => void }) {
// Active only while the dialog is open
useHotkey('Escape', onClose)
return <div role="dialog">...</div>
}For conditions independent of mounting, pass enabled:
useHotkey('Mod+S', () => save(), { enabled: hasUnsavedChanges })When a whole group of shortcuts should toggle together, use a scope instead. See Add providers and scopes.
Element hotkeys#
Hotkeys listen on document by default. To restrict a shortcut to a single element, pass a ref as target:
import { useRef } from 'react'
import { useHotkey } from '@tanstack/react-hotkeys'
function Panel() {
const panelRef = useRef<HTMLDivElement>(null)
// Fires only while the panel (or something inside it) has focus
useHotkey('Escape', () => closePanel(), { target: panelRef })
return (
<div ref={panelRef} tabIndex={0}>
...
</div>
)
}Element hotkeys only fire while the element or a descendant has focus. Add tabIndex={0} if the container isn't focusable.
useRef works when the element renders with the component. If the target mounts later, such as inside a conditionally rendered child, store it in useState via a callback ref instead:
import { useState } from 'react'
function Sidebar() {
const [panel, setPanel] = useState<HTMLDivElement | null>(null)
useHotkey('Escape', () => closePanel(), { target: panel })
return <CollapsiblePanel panelRef={setPanel} />
}See Elements that mount later for details.
Add providers and scopes (optional)#
Without a provider, hotkeys use the built-in defaults and belong to the 'global' scope.
To change default options across your app, add HotkeysProvider at the root:
import { HotkeysProvider } from '@tanstack/react-hotkeys'
function Root() {
return (
<HotkeysProvider defaultOptions={{ hotkey: { timeout: 1500 } }}>
<App />
</HotkeysProvider>
)
}Nest HotkeysProvider with a scope deeper in your tree to group shortcuts together. Marking a scope exclusive suspends every other scope while it's mounted, which works well for modals and confirmation dialogs:
import { HotkeysProvider, useHotkeys } from '@tanstack/react-hotkeys'
function ConfirmDialog(props: ConfirmDialogProps) {
return (
<HotkeysProvider scope="confirm-dialog" exclusive>
<ConfirmDialogBody {...props} />
</HotkeysProvider>
)
}
function ConfirmDialogBody({ onConfirm, onCancel }: ConfirmDialogProps) {
useHotkeys([
{ hotkey: 'Enter', callback: onConfirm },
{ hotkey: 'Escape', callback: onCancel },
])
return <div role="dialog">...</div>
}While the dialog is open, Enter and Escape belong exclusively to it, and background shortcuts pause until it closes.
Note
Hooks read the nearest provider above the component calling them, so render the dialog's hotkeys inside a child of its HotkeysProvider.
See HotkeysProvider & Scopes for nested scope precedence and toggling scopes via enabled.
Next steps#
Core guides:
- Hotkeys: chords and sequences, options, and element hotkeys
- Sequences: Vim-style multi-key shortcuts
- Sensible Defaults: what hotkeys do without options, and keyboard layouts
- Formatting & Display: labels and keycaps for every platform
- HotkeysProvider & Scopes: set default options, and turn groups of hotkeys on and off with dialogs, panes, and tabs
- Devtools: inspect registered hotkeys, scopes, and held keys while you develop
App Hotkeys & UI:
- App Hotkeys: declare hotkeys in one place and let users change them
- Hotkey Recording: record the shortcut a user presses
- Cheat Sheets: list your shortcuts in a help dialog
- Hotkey Hints: show a button's shortcut while the user holds its modifiers
- Held Keys: show which keys are held
Advanced & Integration:
- SSR & Hydration: server-render platform labels and pass app hotkeys from Server Components
- Keyboard Layouts: type-check keys from international layouts
- Testing: reset singleton state and fix the target platform in unit tests
- Hotkey Manager: register and inspect hotkeys outside components