Skip to content

Instantly share code, notes, and snippets.

@corysimmons
Last active January 28, 2023 14:08
Show Gist options
  • Save corysimmons/61c7b34f3f219acfae7b5bc18e9380bf to your computer and use it in GitHub Desktop.
Save corysimmons/61c7b34f3f219acfae7b5bc18e9380bf to your computer and use it in GitHub Desktop.
A simple hook for adding hotkeys to your React app. Piggybacks on keyboardJS for a nicer interface.
import keyboardJS from 'keyboardjs'
import { useEffect } from 'react'
export default function useHotkey(key: string | string[], callback: () => void) {
useEffect(() => {
keyboardJS.bind(key, callback)
return () => keyboardJS.unbind(key, callback)
}, [key, callback])
}
// usage
import useHotkey from './useHotkey'
export default function() {
useHotkey('a + b', () => console.log('you pressed a and b at the same time'))
return <h1>hi</h1>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment