MCPcopy Create free account
hub / github.com/JohannesKlauss/react-hotkeys-hook

github.com/JohannesKlauss/react-hotkeys-hook

Chat with this repo
repository ↗ · DeepWiki ↗ · release v5.4.0 ↗ · + Follow · compare 2 versions
51 symbols 152 edges 27 files ⚖ MIT 0 documented · 0% ● updated 3d agov5.4.0 · 2026-11-09★ 3,50511 open issues

Browse by type

⨍ Functions 46◇ Types & classes 5
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

useHotkeys(keys, callback)

Bundlephobia Types NPM Version MIT License

Sponsored by Spaceteams

npm i react-hotkeys-hook

A React hook for using keyboard shortcuts in components in a declarative way.


Quick Start

```jsx harmony import { useHotkeys } from 'react-hotkeys-hook'

export const ExampleComponent = () => { const [count, setCount] = useState(0) useHotkeys('ctrl+k', () => setCount((prevCount) => prevCount + 1))

return

Pressed {count} times.

}


### Scopes

Scopes allow you to group hotkeys together. You can use scopes to prevent hotkeys from colliding with each other.

```jsx harmony
const App = () => {
  return (
    <HotkeysProvider initiallyActiveScopes={['settings']}>
      <ExampleComponent />
    </HotkeysProvider>
  )
}

export const ExampleComponent = () => {
  const [count, setCount] = useState(0)
  useHotkeys('ctrl+k', () => setCount((prevCount) => prevCount + 1), { scopes: ['settings'] })

  return 

Pressed {count} times.


}

Changing a scope's active state

You can change the active state of a scope using the disableScope, enableScope and toggleScope functions returned by the useHotkeysContext() hook. Note that you have to have your app wrapped in a <HotkeysProvider> component.

```jsx harmony const App = () => { return ( ) }

export const ExampleComponent = () => { const { toggleScope } = useHotkeysContext()

return toggleScope('settings')}>Change scope active state }


### Focus trap

This will only trigger the hotkey if the component is focused.

```tsx harmony
export const ExampleComponent = () => {
  const [count, setCount] = useState(0)
  const ref = useHotkeys<HTMLParagraphElement>('ctrl+k', () => setCount((prevCount) => prevCount + 1))

  return (



      Pressed {count} times.



  )
}

Documentation & Live Examples

API

useHotkeys(keys, callback)

useHotkeys(keys: string | string[], callback: (event: KeyboardEvent, handler: HotkeysEvent) => void, options: Options = {}, deps?: DependencyList)
Parameter Type Required? Default value Description
keys string or string[] required - set the hotkeys you want the hook to listen to. You can use single or multiple keys, modifier combinations, etc. This will either be a string or an array of strings. To separate multiple keys, use a comma. This split key value can be overridden with the splitKey option.
callback (event: KeyboardEvent, handler: HotkeysEvent) => void required - This is the callback function that will be called when the hotkey is pressed. The callback will receive the browsers native KeyboardEvent and the libraries HotkeysEvent.
options Options optional {} Object to modify the behavior of the hook. Default options are given below.
dependencies DependencyList optional undefined If omitted, the latest callback is used on every render. An empty array ([]) keeps the initial callback. With dependencies, the callback is memoised and updated when a dependency changes, much like useCallback in React. Include every outside variable used by the callback in the array.

Options

All options are optional and have a default value which you can override to change the behavior of the hook.

Option Type Default value Description
enabled boolean or (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => boolean true This option determines whether the hotkey is active or not. It can take a boolean (for example a flag from a state outside) or a function which gets executed once the hotkey is pressed. If the function returns false the hotkey won't get executed and all browser events are prevented.
enableOnFormTags boolean or FormTags[] false By default, hotkeys are disabled when a form element is focused. This prevents accidental triggering while the user is typing. Set to true to enable on all form tags, or pass an array of specific tags (e.g. ['input', 'textarea', 'select'])
enableOnContentEditable boolean false Enable hotkeys on elements with the contentEditable attribute set to true
splitKey string + Character that joins keys within a combination (e.g. shift+a). Change this if you need to listen for the + key itself
delimiter string , Character that separates different hotkey combinations mapped to the same callback (e.g. ctrl+a, shift+b)
scopes string or string[] * With scopes you can group hotkeys together. The default scope is the wildcard * which matches all hotkeys. Use the <HotkeysProvider> component to change active scopes.
keyup boolean false Trigger the callback on the browser's keyup event
keydown boolean true Trigger the callback on the browser's keydown event. Set both keyup and keydown to true to trigger on both events
preventDefault boolean or (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => boolean false Prevent the browser's default behavior for the matched keystroke. Useful for overriding shortcuts like meta+s. Note: some browser shortcuts (e.g. meta+w) cannot be overridden
description string undefined Human-readable description of what the hotkey does. Useful for building help panels
useKey boolean false Listen to the produced character instead of the physical key code
ignoreModifiers boolean false Ignore modifier keys when matching hotkeys
sequenceTimeoutMs number 1000 Time window in milliseconds for sequential hotkeys

Overloads

The hooks call signature is very flexible. For example if you don't need to set any special options you can use the dependency array as your third parameter:

useHotkeys('ctrl+k', () => console.log(counter + 1), [counter])

useHotkeysContext()

Access the HotkeysProvider context to inspect the registered hotkeys for the currently active scopes and to control scope activation.

useHotkeysContext(): {
  hotkeys: ReadonlyArray<Hotkey>
  activeScopes: string[]
  toggleScope: (scope: string) => void
  enableScope: (scope: string) => void
  disableScope: (scope: string) => void
}
import { HotkeysProvider, useHotkeys, useHotkeysContext } from 'react-hotkeys-hook'

function EditorHotkeys() {
  useHotkeys('ctrl+s', () => {}, { scopes: 'settings', description: 'Save document' })

  return null
}

function ShortcutList() {
  const { hotkeys, activeScopes, toggleScope } = useHotkeysContext()

  return (
    <>


Active scopes: {activeScopes.join(', ') || 'none'}


      <button onClick={() => toggleScope('settings')}>Toggle settings scope</button>
      <ul>
        {hotkeys.map(({ hotkey, description }) => (
          <li key={hotkey}>
            {hotkey} {description ? `— ${description}` : ''}
          </li>
        ))}
      </ul>
    </>
  )
}

function App() {
  return (
    <HotkeysProvider initiallyActiveScopes={['settings']}>
      <EditorHotkeys />
      <ShortcutList />
    </HotkeysProvider>
  )
}

Note: Wrap your components in a HotkeysProvider to access active scopes and registered hotkeys. Outside a provider,

Extension points exported contracts — how you extend this code

browse all types & interfaces →

Core symbols most depended-on inside this repo

browse all functions →

Shape

Function 45
Interface 3
Class 2
Method 1

Languages

TypeScript100%

Modules by API surface

packages/react-hotkeys-hook/src/test/useHotkeys.test.tsx9 symbols
packages/react-hotkeys-hook/src/lib/validators.ts7 symbols
packages/react-hotkeys-hook/src/lib/useHotkeys.ts6 symbols
packages/react-hotkeys-hook/src/lib/parseHotkeys.ts5 symbols
packages/documentation/src/pages/index.tsx5 symbols
packages/react-hotkeys-hook/src/lib/isHotkeyPressed.ts4 symbols
packages/react-hotkeys-hook/src/lib/HotkeysProvider.tsx3 symbols
packages/react-hotkeys-hook/src/lib/BoundHotkeysProxyProvider.tsx3 symbols
packages/react-hotkeys-hook/src/test/useHotkeysContext.test.tsx2 symbols
packages/react-hotkeys-hook/src/test/HotkeysProvider.test.tsx2 symbols
packages/documentation/src/components/UnreferencedHotkeysNotice.tsx2 symbols
packages/react-hotkeys-hook/src/lib/useRecordHotkeys.ts1 symbols

Dependencies from manifests, versioned

@docusaurus/core3.10.2 · 1×
@docusaurus/preset-classic3.10.2 · 1×
@docusaurus/theme-live-codeblock3.10.2 · 1×
@mdx-js/react3.1.1 · 1×
@svgr/webpack8.1.0 · 1×
@testing-library/react16.3.3 · 1×
@types/node24.19.2 · 1×
@types/react19.2.18 · 1×
@types/react-dom19.2.3 · 1×

For agents

$ claude mcp add react-hotkeys-hook \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page