react-hookseslintusecallbackeslint-plugin-react-hooks

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


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?


Solution

  • 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