Skip to content

Commit

Permalink
Merge pull request #25 from bigbinary/24-fix-the-performance-issues-i…
Browse files Browse the repository at this point in the history
…n-usehotkeys-hook

Fixes the performance issues in useHotkeys hook.
  • Loading branch information
AbhayVAshokan authored Aug 9, 2024
2 parents 842ea48 + ba4a42e commit e82261f
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useEffect, useMemo, useRef } from "react";

import { mergeLeft } from "ramda";

Expand All @@ -11,34 +11,41 @@ import {

const useHotKeys = (hotkey, handler, userConfig, externalDocument) => {
const ref = useRef(null);
const convertedHotkey = convertHotkeyToUsersPlatform(hotkey);
const config = mergeLeft(userConfig, DEFAULT_CONFIG);
const handlerRef = useRef(handler);

if (!handler) {
throw new Error("You must provide a handler function to useHotKeys");
}
handlerRef.current = handler;

const convertedHotkey = useMemo(
() => convertHotkeyToUsersPlatform(hotkey),
[hotkey]
);

const memoizedConfig = useMemo(
() => mergeLeft(userConfig, DEFAULT_CONFIG),
[userConfig?.enabled, userConfig?.mode, userConfig?.unbindOnUnmount]
);

useEffect(() => {
if (!config.enabled) return undefined;
if (!memoizedConfig.enabled) return undefined;

const mousetrapInstance = bindHotKey({
mode: config.mode,
mode: memoizedConfig.mode,
hotkey: convertedHotkey,
handler,
handler: handlerRef.current,
ref,
externalDocument,
});

return () => {
unBindHotKey({
mousetrapInstance,
mode: config.mode,
mode: memoizedConfig.mode,
hotkey: convertedHotkey,
});
};
}, [handler, config.mode, convertedHotkey, config]);
}, [convertedHotkey, externalDocument, memoizedConfig]);

return config.mode === MODES.scoped ? ref : null;
return memoizedConfig.mode === MODES.scoped ? ref : null;
};

export default useHotKeys;

0 comments on commit e82261f

Please sign in to comment.