Why does `react-hooks/exhaustive-deps` lint rule trigger on nested object properties?
Asked Answered
P

1

8

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 warn me in the first example?
Can I safely ignore it in such circumstances?

Paisley answered 22/11, 2019 at 4:34 Comment(6)
Possible Duplicate of How to fix missing dependency warning when using useEffect React Hook?Triple
I took a look, and it's not a duplicate. The function in that question is not being referenced an object.Paisley
@MattHuggins wouldn't the second example throw an error :/ ? You are redeclaring the same var.Precede
@Precede - thanks for pointing that out, I've updated the example to better replicate my scenario.Paisley
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.Nail
That was my sentiment as well. I figured either I'm missing something, or I'm taking crazy pills. :)Paisley
A
8

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

Arcadia answered 6/5, 2020 at 10:28 Comment(1)
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.Paisley

© 2022 - 2025 — McMap. All rights reserved.