Can I use AND (&&) OR ( || ) operators in dependency array React JS

Viewed 1325

Can I use && and/or || operators in dependency array like this:

const isVisible = true
const isModified = false

useEffect(() => console.log("both are true"), [isVisible && isModified])

Is it a bad practice? Eslint says React Hook useEffect has a complex expression in the dependency array. react-hooks/exhaustive-deps

How can I achieve the same result by doing this the right way?

3 Answers

Eslint says lots of stuff. If this is your project and you like that style, change your .eslintrc so that it doesn't flag that. If you are coding to someone else's style, then you should respect it and maybe do:

const isVisible = true
const isModified = false

const combined = [isVisible && isModified]

useEffect(() => console.log("both are true"), combined)

In the example you provided, the code is totally independent, so, it'd be a good idea to remove dependency array.

In case if in the callback you conditionally do things with isVisible or isModified, it means that your code depends on both of this variables. In that case, you'll just need to specify both of them in the dependency array ([isVisible, isModified]).

I think you can achieve the expected result by checking the state of isVisible and isModified within the useEffect callback function. Please look at the following example

const isVisible = true;
const isModified = false;

useEffect(() => {
  if (isVisible && isModified) {
    console.log("both are true");
  }
}, [isVisible, isModified]);
Related