10

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?

6
  • Possible Duplicate of How to fix missing dependency warning when using useEffect React Hook? Commented Nov 22, 2019 at 6:06
  • 2
    I took a look, and it's not a duplicate. The function in that question is not being referenced an object. Commented Nov 22, 2019 at 14:28
  • @MattHuggins wouldn't the second example throw an error :/ ? You are redeclaring the same var. Commented Nov 23, 2019 at 15:40
  • @James - thanks for pointing that out, I've updated the example to better replicate my scenario. Commented Nov 23, 2019 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. Commented Nov 23, 2019 at 17:32

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.