Home > OS >  Use Effect Triggered Multiple Times
Use Effect Triggered Multiple Times

Time:09-16

I'm trying to do a simple setState on a button with a counter and apply different background color depending on its state. It runs perfectly for the first 3 button clicks and on the fourth one and so on it does this: counter log

Here's the code:

useEffect(() => {
    const changePower = () => {
      if (power === 'on') {
        document.getElementById('btn-trigger').style.backgroundColor = "red";
        setPower('off');
      } else if (power==='off') {
        document.getElementById('btn-trigger').style.backgroundColor = "lime";
        setPower('on');
      }
      setCount(count   1);
    }

    document.getElementById('btn-trigger').addEventListener('click', changePower);
    console.log(count);
  }, [power])

Any help would be awesome, Thank You!

CodePudding user response:

you are setting "power" value by "setPower" inside a useEffect who is listening to changes on "power".

CodePudding user response:

You need to clean up the events:

useEffect(() => {
    const changePower = () => {
      if (power === 'on') {
        document.getElementById('btn-trigger').style.backgroundColor = "red";
        setPower('off');
      } else if (power==='off') {
        document.getElementById('btn-trigger').style.backgroundColor = "lime";
        setPower('on');
      }
      setCount(count   1);
    }

    document.getElementById('btn-trigger').addEventListener('click', changePower);
    console.log(count);

    return () => window.removeEventListener("click", changePower) <-----
  }, [power])
  • Related