React: React hooks exhaustive-deps rule also requires functions in useEffect array

Created on 12 May 2019  路  2Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
bug

What is the current behavior?
so I've got following effect

```js
useEffect(() => {
if (disabled) {
setAnimatedValue(0);
} else {
setAnimatedValue(1);
}
}, [disabled]);

That simply animates button to its enabled or disabled state if `disabled` prop changes.

I also added following rule to my eslint config

```json
'react-hooks/exhaustive-deps': 'warn'

Now I'm getting a warning that setAnimatedValue needs to be added to my useEffect array alongside disabled prop, but it is just a function that's neither a state nor a prop, so it shouldn't really go in there as far as I understand.

Is there a way to somehow make this rule only warn if I am missing state or prop value?

What is the expected behavior?
I'm not sure if this is correct behaviour, i.e. if function used inside the effect always has constant values that don't rely on state or props?

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
16.8.6

Most helpful comment

Hi @gaearon, wouldn't it be great if you could call a set* function provided by another hook that declares it with an useState hook? Maybe I'm not understanding something but this is a thing that I'm doing quite often! Thank you in advance.
PS. Love your work!

All 2 comments

Omitting functions is not generally safe:

https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies

However, the set* functions provided by React can generally be omitted because their identity is guaranteed to be stable. If you declared it in useState within the same component, the ESLint rule should be able to detect that. (Are you running the latest version of ESLint plugin?)

Hope that helps.

Hi @gaearon, wouldn't it be great if you could call a set* function provided by another hook that declares it with an useState hook? Maybe I'm not understanding something but this is a thing that I'm doing quite often! Thank you in advance.
PS. Love your work!

Was this page helpful?
0 / 5 - 0 ratings