简体   繁体   中英

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?

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

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