4

I'm trying to use React hooks for memoizing a callback. This callback specifically uses a function that's defined on an object.

const setValue = useCallback((value) => {
  field.setValue(key, value);
}, [field.setValue, key]);

This triggers eslint rule react-hooks/exhaustive-deps. It wants me to instead pass in [field, key].

If I then change the code to the following, I get no warning even though it seems equivalent:

const { setValue: setFieldValue } = field;

const setValue = useCallback((value) => {
  setFieldValue(key, value);
}, [setFieldValue, key]);

Why is eslint warning me in the first example? Can I safely ignore it in such circumstances?

Matt Huggins
  • 78,024
  • 36
  • 145
  • 216
  • Possible Duplicate of [How to fix missing dependency warning when using useEffect React Hook?](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook/55854902#55854902) – Shubham Khatri Nov 22 '19 at 06:06
  • I took a look, and it's not a duplicate. The function in that question is not being referenced an object. – Matt Huggins Nov 22 '19 at 14:28
  • @MattHuggins wouldn't the second example throw an error :/ ? You are redeclaring the same var. – James Nov 23 '19 at 15:40
  • @James - thanks for pointing that out, I've updated the example to better replicate my scenario. – Matt Huggins Nov 23 '19 at 17:13
  • 1
    This seems like a bug in the linting rule to me. In your first example, `field.setValue` is certainly the better thing to pass. If react does deep object equality checking in hooks then this prevents un-necessary checks, and if they don't then passing `field` is just plain incorrect. – schu34 Nov 23 '19 at 17:32
  • That was my sentiment as well. I figured either I'm missing something, or I'm taking crazy pills. :) – Matt Huggins Nov 23 '19 at 18:36

1 Answers1

3

Try this.

const setValue = useCallback((value) => {
  const set = field.setValue;
  set(key, value);
}, [field.setValue, key]);

But it's not recommended.Take a look at this explanation. https://github.com/facebook/react/issues/15924#issuecomment-521253636

HDC
  • 46
  • 3
  • Thanks for official word from Facebook on this. I assumed it had to do with `this` context, but couldn't find anything related to it. – Matt Huggins May 06 '20 at 17:50