react-hotkeys-hook vs react-hotkeys vs react-shortcuts
Keyboard Shortcut Libraries for React Comparison
1 Year
react-hotkeys-hookreact-hotkeysreact-shortcuts
What's Keyboard Shortcut Libraries for React?

These libraries provide mechanisms to manage keyboard shortcuts in React applications, enhancing user experience by allowing users to interact with the application through keyboard commands. They simplify the implementation of keyboard event handling, making it easier to create responsive and accessible applications. Each library offers unique features and approaches to handling keyboard shortcuts, catering to different development needs and preferences.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
react-hotkeys-hook1,005,8802,93333.4 kB256 days agoMIT
react-hotkeys285,9072,161-1086 years agoISC
react-shortcuts15,92732930.1 kB52-MIT
Feature Comparison: react-hotkeys-hook vs react-hotkeys vs react-shortcuts

API Design

  • react-hotkeys-hook:

    react-hotkeys-hook leverages React hooks to provide a simple and intuitive API for managing keyboard shortcuts. It allows developers to easily define shortcuts directly within functional components, promoting a clean and modern coding style while maintaining flexibility and ease of use.

  • react-hotkeys:

    react-hotkeys provides a comprehensive API that allows developers to define keyboard shortcuts in a declarative manner. It supports complex key combinations and offers features like global shortcuts, context-aware shortcuts, and customizable event handling, making it suitable for applications with extensive keyboard interactions.

  • react-shortcuts:

    react-shortcuts offers a straightforward API focused on simplicity. It allows developers to define shortcuts with minimal configuration, making it easy to implement basic keyboard interactions without the overhead of more complex libraries.

Performance

  • react-hotkeys-hook:

    react-hotkeys-hook is designed to be lightweight and efficient, leveraging React's built-in optimizations. It ensures that keyboard event listeners are only active when necessary, reducing unnecessary processing and improving performance in functional components.

  • react-hotkeys:

    react-hotkeys is optimized for performance, allowing efficient handling of keyboard events even in complex applications. It minimizes re-renders and ensures that shortcut handling does not interfere with the application's overall performance, making it suitable for high-performance scenarios.

  • react-shortcuts:

    react-shortcuts is lightweight and has minimal overhead, making it a good choice for applications where performance is critical. It focuses on providing basic functionality without the complexity, ensuring fast response times for keyboard interactions.

Learning Curve

  • react-hotkeys-hook:

    react-hotkeys-hook is easier to learn for developers familiar with React hooks. Its straightforward API and integration with functional components make it accessible for those new to keyboard shortcut management, allowing for quick adoption and implementation.

  • react-hotkeys:

    react-hotkeys has a steeper learning curve due to its comprehensive feature set and API complexity. Developers may need to invest time to fully understand its capabilities and best practices for implementing shortcuts effectively in larger applications.

  • react-shortcuts:

    react-shortcuts is the easiest to learn among the three, as it provides a simple API with minimal configuration. Developers can quickly implement keyboard shortcuts without needing to understand complex concepts, making it ideal for beginners.

Community and Support

  • react-hotkeys-hook:

    react-hotkeys-hook is gaining popularity and has a growing community. While it may not have as extensive resources as react-hotkeys, it benefits from the modern React ecosystem, and developers can find support through forums and GitHub.

  • react-hotkeys:

    react-hotkeys has a strong community and is actively maintained, providing good documentation and support. This makes it easier for developers to find resources, examples, and assistance when implementing keyboard shortcuts in their applications.

  • react-shortcuts:

    react-shortcuts has a smaller community and fewer resources compared to the other two libraries. While it is straightforward to use, developers may find limited support and examples, which could be a consideration for larger projects.

Extensibility

  • react-hotkeys-hook:

    react-hotkeys-hook is designed with extensibility in mind, allowing developers to easily integrate additional functionality or customize behavior through hooks. This enables a modular approach to managing keyboard shortcuts in React applications.

  • react-hotkeys:

    react-hotkeys offers extensive customization options, allowing developers to create complex shortcut systems tailored to their specific needs. This makes it suitable for applications that require a high degree of flexibility in keyboard interactions.

  • react-shortcuts:

    react-shortcuts is less extensible compared to the other libraries, focusing on basic functionality. While it is suitable for simple applications, developers may find it limiting if they need advanced features or custom behaviors.

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

    Opt for react-hotkeys-hook if you prefer a more modern, hook-based approach to managing keyboard shortcuts in functional components. This library is ideal for developers looking for simplicity and ease of integration with React's functional component paradigm, making it a great choice for new projects.

  • react-hotkeys:

    Choose react-hotkeys if you need a robust solution that supports complex key combinations and offers a higher level of customization. It is well-suited for applications that require extensive keyboard shortcut management and provides a clear API for defining and handling shortcuts.

  • react-shortcuts:

    Select react-shortcuts if you need a lightweight solution that focuses on basic shortcut functionality. It is suitable for simpler applications where minimal overhead is desired, and you want to quickly implement keyboard shortcuts without the complexity of more feature-rich libraries.

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