Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda