react-use-hotkeys icon indicating copy to clipboard operation
react-use-hotkeys copied to clipboard

Incompatibility with eslint react-hooks/exhaustive-deps additionalHooks

Open MHebes opened this issue 8 months ago • 0 comments

Hi, love the library. Not sure if it's still being maintained but for posterity:

The official react-hooks/exhaustive-deps eslint rule allows you to whitelist custom hooks to automatically have their dependency lists scanned. See https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#advanced-configuration for an example.

However this only works (for me, at least) if the dependency list comes second in the argument list, matching useEffect(callback, deps).

useHotkeys does not work with this rule. As a workaround I've swapped the order of arguments:

import { useHotkeys } from "react-hotkeys-hook";

type useHotkeysParams = Parameters<typeof useHotkeys>;

// rearranges args so it matches useEffect's signature, and the react-hooks/exhaustive-deps rule picks it up
export function useHotkeysSafe(
  callback: useHotkeysParams[1],
  dependencies: useHotkeysParams[3],
  keys: useHotkeysParams[0],
  options?: useHotkeysParams[2]
) {
  return useHotkeys(keys, callback, options, dependencies);
}

And added this to my .eslintrc.json:

{
  // ...
  "rules": {
    "react-hooks/exhaustive-deps": [
      "warn",
      {
        "additionalHooks": "useHotkeysSafe|useSomeOtherCustomHook"
      }
    ]
  }
}

And we use useHotkeysSafe everywhere. This gives us a warning if our callback uses variables that aren't in the dependency array.

Perhaps the library could allow another overload of useHotkeys supporting this use case. The typings could also be improved to separate the different signatures, rather than allowing a union of each parameter at each argument:

export function useHotkeys<T extends HTMLElement>(keys: Keys, callback: HotkeyCallback, options?: Options, dependencies?: DependencyList): MutableRefObject<RefType<T>>;
export function useHotkeys<T extends HTMLElement>(keys: Keys, callback: HotkeyCallback, dependencies?: DependencyList, options?: Options): MutableRefObject<RefType<T>>;
export function useHotkeys<T extends HTMLElement>(callback: HotkeyCallback, dependencies?: DependencyList, keys: Keys, options?: Options): MutableRefObject<RefType<T>>;

MHebes avatar Jun 04 '24 21:06 MHebes