Created
April 2, 2020 13:50
-
-
Save sarahdayan/47cb88b6a8163500967ffe4c85ad1622 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hotkeys, { HotkeysEvent } from 'hotkeys-js'; | |
import { useEffect, useCallback } from 'preact/hooks'; | |
/** | |
* A Preact hook for triggering side-effects when pressing hotkeys. | |
* | |
* @param keys A comma-separated list of hotkeys to trigger the callback on. | |
* @param callback A callback function to execute when keys are pressed. | |
* @param dependencies A list of dependencies. | |
*/ | |
function useHotkeys<Dependencies>( | |
keys: string, | |
callback: (event: KeyboardEvent, handler: HotkeysEvent) => void, | |
dependencies: Dependencies[] = [] | |
) { | |
const memoizedCallback = useCallback(callback, dependencies); | |
useEffect(() => { | |
hotkeys.filter = () => true; | |
hotkeys(keys, memoizedCallback); | |
return () => hotkeys.unbind(keys); | |
}, [keys, memoizedCallback]); | |
} | |
export default useHotkeys; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment