tanstack-hotkeys

Guide for implementing keyboard shortcuts in React using @tanstack/react-hotkeys. Use when building hotkey/shortcut features, registering keyboard shortcuts, handling key sequences, recording custom shortcuts, tracking held keys, or formatting hotkeys for display in React applications.

7 stars

Best use case

tanstack-hotkeys is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Guide for implementing keyboard shortcuts in React using @tanstack/react-hotkeys. Use when building hotkey/shortcut features, registering keyboard shortcuts, handling key sequences, recording custom shortcuts, tracking held keys, or formatting hotkeys for display in React applications.

Teams using tanstack-hotkeys should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/tanstack-hotkeys/SKILL.md --create-dirs "https://raw.githubusercontent.com/fellipeutaka/denji/main/.agents/skills/tanstack-hotkeys/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/tanstack-hotkeys/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How tanstack-hotkeys Compares

Feature / Agenttanstack-hotkeysStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Guide for implementing keyboard shortcuts in React using @tanstack/react-hotkeys. Use when building hotkey/shortcut features, registering keyboard shortcuts, handling key sequences, recording custom shortcuts, tracking held keys, or formatting hotkeys for display in React applications.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# TanStack Hotkeys (React)

Type-safe keyboard shortcut management for React. Package: `@tanstack/react-hotkeys`.

All framework packages re-export everything from `@tanstack/hotkeys` core — no separate install needed.

## Quick Start

```tsx
import { useHotkey } from '@tanstack/react-hotkeys'

function App() {
  useHotkey('Mod+S', () => saveDocument())
  return <div>Press Cmd+S (Mac) or Ctrl+S (Windows) to save</div>
}
```

`Mod` resolves to `Meta` (Cmd) on macOS, `Control` on Windows/Linux.

## Core Hooks

### `useHotkey(hotkey, callback, options?)`

Primary hook. Accepts string (`'Mod+S'`) or `RawHotkey` object (`{ key: 'S', mod: true }`).

Callback receives `(event: KeyboardEvent, context: { hotkey, parsedHotkey })`.

Auto-syncs callback every render (no stale closures). Auto-cleans up on unmount.

```tsx
// String form
useHotkey('Mod+S', () => save())

// Object form
useHotkey({ key: 'S', mod: true }, () => save())

// Conditional
useHotkey('Escape', () => onClose(), { enabled: isOpen })

// Scoped to element (must be focusable — add tabIndex)
const ref = useRef<HTMLDivElement>(null)
useHotkey('Escape', () => close(), { target: ref })
```

**Default options:**

| Option | Default | Notes |
|---|---|---|
| `enabled` | `true` | |
| `preventDefault` | `true` | Overrides browser defaults like Cmd+S |
| `stopPropagation` | `true` | |
| `eventType` | `'keydown'` | Also supports `'keyup'` |
| `requireReset` | `false` | When true, fires once until all keys released |
| `ignoreInputs` | smart | `false` for Ctrl/Meta combos & Escape; `true` for single keys & Shift/Alt combos |
| `target` | `document` | Accepts DOM element, `window`, or React ref |
| `conflictBehavior` | `'warn'` | `'error'`, `'replace'`, `'allow'` |

### `useHotkeySequence(sequence, callback, options?)`

Vim-style multi-key sequences. Keys pressed in order within timeout.

```tsx
useHotkeySequence(['G', 'G'], () => scrollToTop())
useHotkeySequence(['D', 'I', 'W'], () => deleteInnerWord(), { timeout: 500 })

// With modifiers
useHotkeySequence(['Mod+K', 'Mod+C'], () => commentSelection())
```

Options: `timeout` (default 1000ms), `enabled` (default true).

Overlapping prefixes work — manager tracks each independently.

### `useHotkeyRecorder(options)`

Record custom shortcuts. Returns `{ isRecording, recordedHotkey, startRecording, stopRecording, cancelRecording }`.

- Escape cancels recording
- Backspace/Delete clears recorded hotkey
- Auto-converts to portable `Mod` format (Meta+S becomes Mod+S)

```tsx
const recorder = useHotkeyRecorder({
  onRecord: (hotkey) => setShortcut(hotkey),
  onCancel: () => console.log('cancelled'),
  onClear: () => console.log('cleared'),
})
```

### Key State Tracking

```tsx
// All held keys
const heldKeys = useHeldKeys() // string[]

// Single key check (optimized — only re-renders when this key changes)
const isShiftHeld = useKeyHold('Shift') // boolean

// Key-to-code mapping (distinguish left/right modifiers)
const codes = useHeldKeyCodes() // Record<string, string>
```

## Display Formatting

```tsx
import { formatForDisplay, formatWithLabels } from '@tanstack/react-hotkeys'

// Platform-aware symbols
formatForDisplay('Mod+S')        // Mac: "⌘S" | Windows: "Ctrl+S"
formatForDisplay('Mod+Shift+Z')  // Mac: "⇧⌘Z" | Windows: "Ctrl+Shift+Z"

// Text labels
formatWithLabels('Mod+S')        // Mac: "Cmd+S" | Windows: "Ctrl+S"
```

Use in UI:

```tsx
<button>Save <kbd>{formatForDisplay('Mod+S')}</kbd></button>
```

## `HotkeysProvider`

Set global defaults for all hooks. Per-hook options override.

```tsx
import { HotkeysProvider } from '@tanstack/react-hotkeys'

<HotkeysProvider defaultOptions={{
  hotkey: { preventDefault: true },
  hotkeySequence: { timeout: 1500 },
  hotkeyRecorder: { onCancel: () => console.log('cancelled') },
}}>
  <App />
</HotkeysProvider>
```

## Devtools

```sh
npm install @tanstack/react-devtools @tanstack/react-hotkeys-devtools
```

```tsx
import { TanStackDevtools } from '@tanstack/react-devtools'
import { hotkeysDevtoolsPlugin } from '@tanstack/react-hotkeys-devtools'

<TanStackDevtools plugins={[hotkeysDevtoolsPlugin()]} />
```

Auto-excluded from production builds. Use `@tanstack/react-hotkeys-devtools/production` import to include in prod.

## Key Patterns

- **Scoped hotkeys**: Pass `target: ref` + ensure element has `tabIndex`
- **Conditional**: Use `enabled` option tied to state
- **Multiple hotkeys**: Each `useHotkey` call is independent
- **Shortcut settings UI**: Combine `useHotkeyRecorder` + `useHotkey` with dynamic bindings + `formatForDisplay`
- **Hold-to-reveal UI**: Use `useKeyHold` to conditionally render elements
- **Shortcut hints overlay**: Show overlay when modifier held via `useKeyHold`

## API Reference

For complete API details including all interfaces, types, utility functions, and core classes, see [references/react-api.md](references/react-api.md).

Related Skills

tanstack-virtual

7
from fellipeutaka/denji

TanStack Virtual headless virtualization for React. Use when rendering large lists (100+ items), implementing virtual scroll, building infinite scroll feeds, virtualizing grids or tables, using window-level scrolling, or implementing masonry/lane layouts with @tanstack/react-virtual. Triggers on: useVirtualizer, useWindowVirtualizer, virtual list, virtual scroll, list virtualization.

tanstack-query

7
from fellipeutaka/denji

TanStack Query (React Query) v5 best practices for data fetching, caching, mutations, and server state management. Use when building data-driven React applications, setting up query configurations, implementing mutations/optimistic updates, configuring caching strategies, integrating with SSR, or fixing v4→v5 migration errors.

tanstack-pacer

7
from fellipeutaka/denji

TanStack Pacer best practices for execution control in React — debouncing, throttling, rate limiting, queuing, and batching. Use when implementing search inputs, scroll handlers, API rate limits, task queues, bulk operations, or any scenario requiring controlled execution timing with reactive state.

solid

7
from fellipeutaka/denji

Apply SOLID principles to write flexible, maintainable, and testable code. Use when designing classes, interfaces, and module boundaries. Covers Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion with practical TypeScript examples and detection heuristics.

denji

7
from fellipeutaka/denji

Manage SVG icons as framework components using Denji CLI. Use when the user needs to add, remove, list, export, import, or manage SVG icons in React, Preact, Solid, Qwik, Vue, or Svelte projects. Triggers include requests to "add an icon", "set up icons", "manage SVG icons", "remove an icon", "list icons", "export icons", "import icons", "dry-run icon add", or any task involving Iconify icons as framework components.

zod

7
from fellipeutaka/denji

Zod 4 — TypeScript-first schema validation with static type inference. Use when writing Zod schemas, validating data, defining types with Zod, parsing input, creating form validation schemas, defining API request/response schemas, working with z.object, z.string, z.number, z.enum, z.array, z.union, z.discriminatedUnion, z.file, z.jwt, z.email, z.uuid, z.url, z.codec, z.toJSONSchema, z.fromJSONSchema, z.int, z.stringbool, z.templateLiteral, z.record, z.partialRecord, or any other Zod API. Also use when migrating from Zod 3 to Zod 4, or when the user's package.json shows zod@^4. CRITICAL: Always use Zod 4 APIs. Never use deprecated Zod 3 patterns unless user explicitly requests Zod 3 compatibility.

web-design-guidelines

7
from fellipeutaka/denji

Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".

vercel-react-best-practices

7
from fellipeutaka/denji

React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

vercel-composition-patterns

7
from fellipeutaka/denji

React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.

turborepo

7
from fellipeutaka/denji

Turborepo monorepo build system guidance. Triggers on: turbo.json, task pipelines, dependsOn, caching, remote cache, the "turbo" CLI, --filter, --affected, CI optimization, environment variables, internal packages, monorepo structure/best practices, and boundaries. Use when user: configures tasks/workflows/pipelines, creates packages, sets up monorepo, shares code between apps, runs changed/affected packages, debugs cache, or has apps/packages directories.

skill-creator

7
from fellipeutaka/denji

Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.

seo-audit

7
from fellipeutaka/denji

When the user wants to audit, review, or diagnose SEO issues on their site. Also use when the user mentions "SEO audit," "technical SEO," "why am I not ranking," "SEO issues," "on-page SEO," "meta tags review," or "SEO health check." For building pages at scale to target keywords, see programmatic-seo. For adding structured data, see schema-markup.