12

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.

Brandon
  • 1,735
  • 2
  • 22
  • 37
  • There is a bug actually, you don't want to `...` your deps: ((x,y,...z) =>[x,y,z])(1,2,[3]) === [1,2,[[3]]] – Luke Miles Jul 13 '21 at 20:06
  • Ah, that's a good point. I think I was originally planning to pass a list of deps as regular arguments but you can see in my usage example that I didn't end up doing that. Nice catch! – Brandon Jul 15 '21 at 21:41

1 Answers1

20

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"
    }]
  }
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320