Skip to content

Commit e82261f

Browse files
Merge pull request #25 from bigbinary/24-fix-the-performance-issues-in-usehotkeys-hook
Fixes the performance issues in useHotkeys hook.
2 parents 842ea48 + ba4a42e commit e82261f

1 file changed

Lines changed: 19 additions & 12 deletions

File tree

src/index.js

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useRef } from "react";
1+
import { useEffect, useMemo, useRef } from "react";
22

33
import { mergeLeft } from "ramda";
44

@@ -11,34 +11,41 @@ import {
1111

1212
const 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

4451
export default useHotKeys;

0 commit comments

Comments
 (0)