facebook / react

The library for web and native user interfaces.

Home Page:https://react.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[react-hooks/exhaustive-deps] option request: ignoreFunctions or ignoreMethods

rattrayalex opened this issue · comments

What I would like:

    "react-hooks/exhaustive-deps": ["error", {
      "ignoreFunctions": true
    }]

results in:

const history = useHistory();
const log = (x) => console.log(x)

useEffect(() => {
  log(props.foo); // no error
  props.onChange(props.foo); // no error
  history.push(props.foo) // no error
  
  log(props.bar); // error!
}, [props.foo]);

Why:

I typically do not want to re-execute an effect just because a function I call inside the effect changes its identity. Same with an object which is only used to call a method.

I noticed this with react-router's history.push() – I want to navigate based on other things, not whether react-router has decided that the history object or its push method have changed identity (in the abstract, I can't control or predict a library's behavior in this way).

There may be some codebases where it is typical to wish to re-execute an effect when a method's object or function changes its identity, which is why I suspect this should be an option rather than the default behavior.

Motivating example:

This was the code I was writing which inspired this:

import { useHistory, useParams } from "react-router";
...
const { subpage } = useParams();
const history = useHistory();

useEffect(() => {
  // I don't want to re-run this effect if `history` changes.
  if (!subpage) {
    history.push(`/my-page/my-default-subpage`);
  }
}, [subpage]);

However, I believe that this change would also assuage the desires of participants in this issue: #16265

commented

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

We'd really like to see this as well - we don't current use exhaustive-deps because of this.

Would ignoring functions cause any issues? Or would this be (relatively) safe to do?

commented

It would most definitely not be safe to do. A function can close over props or state, so you'd keep "seeing" their old versions.

We have a different solution in mind for this.

We have a different solution in mind for this.

@gaearon is there an RFC/link to the proposal somewhere?

commented

Any updates on this? According to this thread, it's dangerous to add router as a dependency so I would like the rule to ignore it.