react-hotkeys-hook vs react-shortcuts
React Keyboard Shortcuts Libraries Comparison
1 Year
react-hotkeys-hookreact-shortcutsSimilar Packages:
What's React Keyboard Shortcuts Libraries?

Keyboard shortcuts libraries for React provide developers with the ability to easily implement keyboard interactions in their applications. These libraries allow for the binding of keyboard events to specific actions, enhancing user experience by enabling quick navigation and command execution through keyboard inputs. They help streamline workflows and improve accessibility, making applications more intuitive for users who prefer keyboard navigation over mouse interactions.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
react-hotkeys-hook953,8322,857203 kB634 months agoMIT
react-shortcuts12,88432930.1 kB52-MIT
Feature Comparison: react-hotkeys-hook vs react-shortcuts

API Design

  • react-hotkeys-hook:

    react-hotkeys-hook provides a simple and intuitive API based on React hooks, allowing developers to define keyboard shortcuts directly within their functional components. This design promotes a clean and declarative way to handle keyboard events, making it easier to manage shortcuts in a modular fashion.

  • react-shortcuts:

    react-shortcuts offers a more structured API that allows for centralized management of keyboard shortcuts. It enables developers to define shortcuts in a single location and apply them across multiple components, which can be advantageous for larger applications with complex shortcut requirements.

Ease of Use

  • react-hotkeys-hook:

    With its hook-based approach, react-hotkeys-hook is easy to integrate into existing functional components without the need for additional boilerplate code. This makes it particularly appealing for developers familiar with React hooks and looking for a quick solution to implement keyboard shortcuts.

  • react-shortcuts:

    react-shortcuts may require a bit more setup due to its centralized management system, but it provides a clear structure for defining and managing shortcuts. This can be beneficial for teams working on larger projects where consistency and organization are key.

Performance

  • react-hotkeys-hook:

    react-hotkeys-hook is designed to be lightweight and efficient, minimizing the performance overhead associated with managing keyboard events. Its hook-based nature ensures that only the necessary components re-render when shortcuts are triggered, leading to better performance in applications with frequent keyboard interactions.

  • react-shortcuts:

    react-shortcuts may introduce some overhead due to its centralized management system, but it is optimized for handling a large number of shortcuts efficiently. It is suitable for applications that require extensive keyboard interaction without significant performance degradation.

Flexibility

  • react-hotkeys-hook:

    react-hotkeys-hook offers flexibility in defining shortcuts directly within components, allowing for dynamic and context-specific keyboard interactions. This flexibility is ideal for applications that need to change shortcuts based on user actions or states.

  • react-shortcuts:

    react-shortcuts provides a more rigid structure for managing shortcuts, which can be beneficial for maintaining consistency across an application. However, it may be less flexible in scenarios where shortcuts need to be defined dynamically.

Community and Support

  • react-hotkeys-hook:

    react-hotkeys-hook has a growing community and is actively maintained, providing a good level of support and documentation for developers. Its simplicity and adherence to modern React practices make it a popular choice among developers.

  • react-shortcuts:

    react-shortcuts has a smaller community compared to react-hotkeys-hook, but it is still well-documented and maintained. It may not have as many resources available, but its structured approach can be advantageous for teams looking for a comprehensive solution.

How to Choose: react-hotkeys-hook vs react-shortcuts
  • react-hotkeys-hook:

    Choose react-hotkeys-hook if you need a lightweight solution that leverages React hooks for managing keyboard shortcuts. It is particularly beneficial for functional components and offers a straightforward API for defining and handling key combinations directly within your components.

  • react-shortcuts:

    Choose react-shortcuts if you require a more comprehensive solution that supports complex shortcut management across different components and contexts. It provides a higher-level abstraction for managing shortcuts and can be useful in applications with extensive keyboard interaction requirements.

README for react-hotkeys-hook

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

The easiest way to use the hook.

import { useHotkeys } from 'react-hotkeys-hook'

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

  return (
    <p>
      Pressed {count} times.
    </p>
  )
}

Scopes

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

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 (
    <p>
      Pressed {count} times.
    </p>
  )
}

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.

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

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

  return (
    <button onClick={() => toggleScope('settings')}>
      Change scope active state
    </button>
  )
}

Focus trap

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

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

  return (
    <p tabIndex={-1} ref={ref}>
      Pressed {count} times.
    </p>
  )
}

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 | [] | The given callback will always be memoised inside the hook. So if you reference any outside variables, you need to set them here for the callback to get updated (Much like useCallback works in React). |

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 not registered if a focus focuses on an input field. This will prevent accidental triggering of hotkeys when the user is typing. If you want to enable hotkeys, use this option. Setting it to true will enable on all form tags, otherwise you can give an array of form tags to enable the hotkey on (possible options are: ['input', 'textarea', 'select']) | | enableOnContentEditable | boolean | false | Set this option to enable hotkeys on tags that have set the contentEditable prop to true | | combinationKey | string | + | Character to indicate keystrokes like shift+c. You might want to change this if you want to listen to the + character like ctrl-+. | | splitKey | string | , | Character to separate different keystrokes like ctrl+a, ctrl+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 | Determines whether to listen to the browsers keyup event for triggering the callback. | | keydown | boolean | true | Determines whether to listen to the browsers keydown event for triggering the callback. If you set both keyupand keydown to true, the callback will trigger on both events. | | preventDefault | boolean or (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => boolean | false | Set this to a true if you want the hook to prevent the browsers default behavior on certain keystrokes like meta+s to save a page. NOTE: Certain keystrokes are not preventable, like meta+w to close a tab in chrome. | | description | string | undefined | Use this option to describe what the hotkey does. this is helpful if you want to display a list of active hotkeys to the user. |

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])

isHotkeyPressed(keys: string | string[], splitKey?: string = ',')

This function allows us to check if the user is currently pressing down a key.

import { isHotkeyPressed } from 'react-hotkeys-hook'

isHotkeyPressed('esc') // Returns true if Escape key is pressed down.

You can also check for multiple keys at the same time:

isHotkeyPressed(['esc', 'ctrl+s']) // Returns true if Escape or Ctrl+S are pressed down.

Support

Found an issue or have a feature request?

Open up an issue or pull request and participate.

Local Development

Checkout this repo, run yarn or npm i and then run the test script to test the behavior of the hook.

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Johannes Klauss - @JohannesKlauss - klauss.johannes@gmail.com

Project Link: https://github.com/JohannesKlauss/react-hotkeys-hook

Contributors