Home > Net >  How to prevent useEffect to be fired up in some events?
How to prevent useEffect to be fired up in some events?

Time:12-06

Halo guys, I would like to ask a frustating problem for me :'(

What if we don't want to trigger useEffect in some events for the same state. For example lets say I have a state called "myState" and I have put myState in useEffect's dependency. In button1 I want to update myState which will trigger useEffect, in button2 I want also update myState but I don't want to trigger the useEffect

Is it possible to prevent useEffect to be fired up such I just described?

Thank you

CodePudding user response:

Write UseEffects separately, you can keep on stacking them on one above others if you want to run them independantly

CodePudding user response:

in your state, you should have some kind of a breaker for useEffect. in my example i named it stopUseEffect. if i don't want the useEffect to run, i will set stopUseEffect to true. then in useEffect, first thing to do is to check the breaker, does breaker allow it to run or not (if(myState.stopUseEffect) return;):

const { useState, useEffect } = React

const Test = () => {
  const [myState, setMyState] = useState({content: 0, stopUseEffect: false});
  
  useEffect(() => {
    if(myState.stopUseEffect) return;
    
    console.log("useEffect ran! myState's content:", myState.content)
  }, [myState])

  return <div>
    <button onClick={() => setMyState(p => ({...p, content: p.content   1, stopUseEffect: false}))}>btn 1, this button will trigger useEffect.</button> <br/>
    <button onClick={() => setMyState(p => ({...p, content: p.content   1, stopUseEffect: true}))}>btn 2, this button will NOT trigger useEffect.</button>
</div>
}

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <Test />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related