Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
Use Effect Triggered Multiple Times

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If you set Power in the useEffect, it will trigger itself.

useEffect(() => {
   if(count%2)
      document.getElementById('btn-trigger').style.backgroundColor = "red";
   else
      document.getElementById('btn-trigger').style.backgroundColor = "lime";
   }, [count])

const handeClick = () => {
  setCount(count + 1);
}
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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])

In addition: the changePower function should be declared outside of the useEffect hook. You use the useCallback hook here.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!