Search code examples
reactjsreact-hookseslinteslint-plugin-react-hooks

Can I have react-hooks/exhaustive-deps for a custom hook?


I wrote this hook (there could be bugs, I haven't used it yet):

import { useCallback, useEffect } from 'react';
import _throttle from 'lodash/throttle';

export function useThrottledCallback(cb, delay, ...deps) {
  const callback = useCallback(_throttle(cb, delay), deps);

  useEffect(() => {
    const lastCallback = callback;

    return () => lastCallback.cancel();
  }, [callback]);

  return callback;
}

Is there a way I can make the exhaustive-deps rule lint usages of this hook?

useThrottledCallback(() => (a + b + c)}, 100, [])

In this usage, I'd like to be notified that a, b, and c need to be in the dependency array.


Solution

  • It should be pretty easy. The documentation says:

    exhaustive-deps can be configured to validate dependencies of custom Hooks with the additionalHooks option. This option accepts a regex to match the names of custom Hooks that have dependencies.

    So you'd want something like:

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