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

215
Visualizações
State not resetting. Why is it running concurrently when reset is pressed?

I am learning react. When I click the reset timer button, instead of resetting the timer, a new second timer starts running concurrently. If I click the same button the third time, a new third timer starts at zero also running concurrently.

The same is happening when I click another button that says Jump 10 seconds. It's like its creating a new state instead of resetting the state.

Here is my app.jss code

function App() {

  const [timeSpent, setTimeSpent] = useState(0);

  setTimeout(() => setTimeSpent(timeSpent + 1),
    1000
  )

  //Reset the timer
  const resetTimer = () => setTimeSpent(0);

  return (
    <>

      <Timer secondsPassed={timeSpent} />

      <button onClick={resetTimer}>Reset Timer</button>
      <button onClick={() => setTimeSpent(timeSpent +10)}>Jump 10 Seconds</button>
    </>
  );
}

export default App;

Here is my Timer.js code

function Timer({secondsPassed}) {

    const formatting = () => {
        if (secondsPassed < 60) {
            return secondsPassed + ' Sec';
        } else {
            return Math.floor(secondsPassed/60) + ' Mins';
        }
    }

    return (
        <div>
            <h3>Time Spent: {formatting()}</h3>
        </div>
    )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Based on @Emile Bergeron comment, you should use setInterval inside a useEffect and for updating the state you should get the latest timeSpent which has been passed into the callback function that I passed to setTimeSpent.

 const {useState, useEffect} = React;
 
function App() {
  const [timeSpent, setTimeSpent] = useState(0);
  useEffect(() => {
    setInterval(() => setTimeSpent((time) => time + 1), 1000);
  }, []);

  //Reset the timer
  const resetTimer = () => setTimeSpent(0);

  return (
    <div>
      <Timer secondsPassed={timeSpent} />

      <button onClick={resetTimer}>Reset Timer</button>
      <button onClick={() => setTimeSpent(timeSpent + 10)}>
        Jump 10 Seconds
      </button>
    </div>
  );
}

function Timer({ secondsPassed }) {
  const formatting = () => {
    if (secondsPassed < 60) {
      return secondsPassed + " Sec";
    } else {
      return Math.floor(secondsPassed / 60) + " Mins";
    }
  };

  return (
    <div>
      <h3>Time Spent: {formatting()}</h3>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />,
  rootElement
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

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