问题
Hello I am trying to use a UseEffect of react hooks, I know I can add variables that on change can activate it, but I would like to know if there is a way to activate the useEffect only when the value meets certain criteria.
I have already created a conditional inside the useEffect and I know it works, but I would like to know if there's another way to do it.
useEffect(() => {
doSomething();
if(!isOpen)
doSomething2();
}, [isOpen, otherThing]);
In the example above I want doSomething2 to work only when its value is false.
isOpen in this examample has a default value of false, then when it retrieves something from the database it turns into true and finally when it finished fetching it goes back to false.
I expect the hook to activate only when the value switches from true to false and not in every change.
Is there a way to do that?
回答1:
No other way. Your attempt is already correct. That's the only way. Cheers!
useEffect()
only allows dependencies and no conditional attributes.
来源:https://stackoverflow.com/questions/58575722/can-i-use-a-useeffect-only-with-a-certain-value