Some apps hide shortcut badges until the user holds a modifier key, keeping buttons clean while still making shortcuts discoverable on demand.
useHotkeyHint returns true while the user holds modifiers belonging to an active hotkey. It's an optional display helper and doesn't register a shortcut itself, so pair it with useHotkey.
import {
useFormatForDisplay,
useHotkey,
useHotkeyHint,
} from '@tanstack/preact-hotkeys'
const saveHotkey = 'Mod+S'
function SaveButton() {
const formatForDisplay = useFormatForDisplay()
useHotkey(saveHotkey, save)
const showHint = useHotkeyHint(saveHotkey)
return (
<button onClick={save}>
Save {showHint && <kbd>{formatForDisplay(saveHotkey)}</kbd>}
</button>
)
}Holding Command on macOS or Control elsewhere reveals Save ⌘ S or Save Ctrl+S. See Formatting & Display for formatting options.
const showHint = useHotkeyHint('Alt+Shift+[KeyK]', { exact: true }) // Requires Alt AND ShiftSequences reveal their hint while the user holds the modifiers of their first step:
const showHint = useHotkeyHint(['Mod+K', 'Mod+C']) // true while Mod is heldPass an app hotkey directly so hints stay synchronized even when users rebind shortcuts. Unassigned app hotkeys never show a hint. A small shared <Hint> component keeps buttons tidy:
import {
useAppHotkeys,
useFormatForDisplay,
useHotkey,
useHotkeyHint,
} from '@tanstack/preact-hotkeys'
import type { AppHotkeyId } from '@tanstack/preact-hotkeys'
function Hint({ id }: { id: AppHotkeyId }) {
const formatForDisplay = useFormatForDisplay()
const appHotkey = useAppHotkeys()[id]
const showHint = useHotkeyHint(appHotkey)
return showHint && appHotkey.hotkey ? (
<kbd>{formatForDisplay(appHotkey.hotkey)}</kbd>
) : null
}
function Toolbar() {
useHotkey(useAppHotkeys()['doc.save'], save)
return (
<button onClick={save}>
Save <Hint id="doc.save" />
</button>
)
}Outside Preact components, such as canvas draw loops, combine matchesHeldModifiers with getKeyStateTracker() and getHotkeyManager().hasActiveRegistration():
import {
getHotkeyManager,
getKeyStateTracker,
matchesHeldModifiers,
} from '@tanstack/preact-hotkeys'
const tracker = getKeyStateTracker()
matchesHeldModifiers('Mod+S', tracker.getHeldKeys()) // true while Mod is held
const showHint =
matchesHeldModifiers('Mod+S', tracker.getHeldKeys()) &&
getHotkeyManager().hasActiveRegistration('Mod+S') // Same check as useHotkeyHintSee Held Keys for the tracker and the other held-key hooks, and the Kitchen Sink example for hints on live buttons.