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

143
Visualizações
React click handlers not updating variable

[EDIT] - Added a bit more detail to the code sample.

I'm trying to build a timer component. This is my code.

const Timer = () => {
  let startTime;

  const handleStart = () => {
    startTime = Date.now();
    console.log(startTime);
  };

  const handleEnd = () => {
    console.log(startTime);
  };

  return (
    <>
      <button
        onClick={handleStart}
      >
        Start timer
      </button>

      <button
        onClick={handleEnd}
      >
        End timer
      </button>
    </>
  )
}

handleStart is the click handler for one button and handleEnd is the click handler for the second button.

The problem

When I click the first button to start the timer, everything works and the value of startTime is logged to the console, so I know it has been assigned. However, when I click the second button to stop the timer, it doesn't log startTime. Instead, the console output is undefined.

I have no idea why this is happening. Can someone explain why this code isn't working?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In React, you can't just assign a value to a variable, you have to set the state, like the example below:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [startTime, setStartTime] = useState();

  const handleStart = () => {
    const dateNow = Date.now();
    console.log(dateNow);
    setStartTime(dateNow);
  };

  const handleEnd = () => {
    console.log(startTime);
  };

  return (
    <div className="App">
      <button type="button" onClick={handleStart}>
        Start
      </button>
      <button type="button" onClick={handleEnd}>
        End
      </button>
      <p>{startTime}</p>
    </div>
  );
}

Example in codebox

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