简体   繁体   中英

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.

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"
    }]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM