Can I use a “UseEffect” only with a certain value?

点点圈 提交于 2021-01-28 12:42:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!