react: Bug: eslint(react-hooks/exhaustive-deps) wrong deps with optional chained function calls

React version: 16.13.1

Steps To Reproduce

Every time optional chaining is used with a function call, the function itself is detected by the rule.

// users is optional...
const someContext = {
    users: Math.random() > 0.5 ? [{name: 'test'}] : undefined,
};

const filteredUsers = useMemo(() => {
    return someContext.users?.filter((u) => u.name.startsWith('a'));
}, [someContext.users]);

The current behavior

v4.0.1 and above of eslint-plugin-react-hooks tells me to change the dep to someContext.users?.filter.

The expected behavior

Allow me to keep using someContext.users. I can imagine scenarios where I would want the looked up symbol, but that’s probably less common than depending on the uniqueness of the instance.

Observations

Probably regressed due to https://github.com/facebook/react/pull/18820, but I’m not sure.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 16
  • Comments: 17 (2 by maintainers)

Most upvoted comments

still happening in eslint-plugin-react-hooks@4.0.4

Still happening here too. The fix seems to only work for useEffect. useMemo and useCallback are still triggering the same warnings:

useEffect(() => {
  console.log(a?.b);
}, [a]) // No errors

var c = useMemo(() => {
  return a?.b;
}, [a]) // React Hook useMemo has an unnecessary dependency: 'a'. Either exclude it or remove the dependency array

If I remove [a] in the useMemo version, it then tells me I need to add a?.b as a dependency.

thanks for the fix!

Oh my bad. formValues?.nodeIds?.every(({id}) => id) ?? true