Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda