Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Warn for arrays resulting of .map() or .filter() in hook dependencies #31538

Open
xiniria opened this issue Nov 14, 2024 · 1 comment
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@xiniria
Copy link

xiniria commented Nov 14, 2024

ESLint plugin react hooks version: 4.6.0

Steps To Reproduce

const MyComponent = () => {
  const array = useMemo(() => ["banana", "apple"], []);

  const filteredArray = array.filter((element) => element !== "apple");

  useEffect(() => {
    console.log("If this is printed, array has changed");
  }, [array]);

  useEffect(() => {
    console.log("If this is printed, filteredArray has changed");
  }, [filteredArray]);

  const [counter, setCounter] = useState(0);

  return <button onClick={() => setCounter(counter + 1)}>Re-render</button>;
};

Feature request

The exhaustive-deps rule already warns for functions declared in the scope of a component, which will be re-declared at each render and thus be a problem if put inside the dependency array of a useEffect, useCallback or useMemo. I recently had a problem when applying the .filter() method on a memoized array, since the new resulting array is a new one at each render.

I was wondering if it would be possible to warn for this kind of issues as well, the same way functions declared inside the component are currently warned.

I don't have an exhaustive list of such methods (that return a new object from a given one) that would be warned, other than .filter() and .map(), perhaps people in the comments can propose others?

Where to do this

I have dived a little bit in the code of the package and found the scanForConstructions function (here) that seems to be the one that checks for the functions. If this is the way to do it, I could try to implement this other behaviour in this same function.

@xiniria xiniria added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Nov 14, 2024
@hernandemonteiro

This comment was marked as spam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

2 participants