1- import { useEffect , useRef } from "react" ;
1+ import { useEffect , useMemo , useRef } from "react" ;
22
33import { mergeLeft } from "ramda" ;
44
@@ -11,34 +11,41 @@ import {
1111
1212const useHotKeys = ( hotkey , handler , userConfig , externalDocument ) => {
1313 const ref = useRef ( null ) ;
14- const convertedHotkey = convertHotkeyToUsersPlatform ( hotkey ) ;
15- const config = mergeLeft ( userConfig , DEFAULT_CONFIG ) ;
14+ const handlerRef = useRef ( handler ) ;
1615
17- if ( ! handler ) {
18- throw new Error ( "You must provide a handler function to useHotKeys" ) ;
19- }
16+ handlerRef . current = handler ;
17+
18+ const convertedHotkey = useMemo (
19+ ( ) => convertHotkeyToUsersPlatform ( hotkey ) ,
20+ [ hotkey ]
21+ ) ;
22+
23+ const memoizedConfig = useMemo (
24+ ( ) => mergeLeft ( userConfig , DEFAULT_CONFIG ) ,
25+ [ userConfig ?. enabled , userConfig ?. mode , userConfig ?. unbindOnUnmount ]
26+ ) ;
2027
2128 useEffect ( ( ) => {
22- if ( ! config . enabled ) return undefined ;
29+ if ( ! memoizedConfig . enabled ) return undefined ;
2330
2431 const mousetrapInstance = bindHotKey ( {
25- mode : config . mode ,
32+ mode : memoizedConfig . mode ,
2633 hotkey : convertedHotkey ,
27- handler,
34+ handler : handlerRef . current ,
2835 ref,
2936 externalDocument,
3037 } ) ;
3138
3239 return ( ) => {
3340 unBindHotKey ( {
3441 mousetrapInstance,
35- mode : config . mode ,
42+ mode : memoizedConfig . mode ,
3643 hotkey : convertedHotkey ,
3744 } ) ;
3845 } ;
39- } , [ handler , config . mode , convertedHotkey , config ] ) ;
46+ } , [ convertedHotkey , externalDocument , memoizedConfig ] ) ;
4047
41- return config . mode === MODES . scoped ? ref : null ;
48+ return memoizedConfig . mode === MODES . scoped ? ref : null ;
4249} ;
4350
4451export default useHotKeys ;
0 commit comments