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

151
Visualizações
React - Live Clock Doesn't Work With Initial Value Different Than 0

I am trying to build a live clock with react for a weather app that will update the time in real time instead of only while refreshing the page.

I managed to update the clock in real time but the problem is that it works only when initial value in useState is set to 0.

Declerations:

var today = new Date();
const [seconds, setSeconds] = useState(0);

useEffect:

useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(today.getSeconds());
    }, 1000);
    return () => clearInterval(interval);
  }, [seconds]);

This code works great, the problem is that since the initial value is 0 - the seconds jump from 0 to 37 for example and only then start updating.

When I try to change the initial value for instance:

const [seconds, setSeconds] = useState(today.getSeconds());

The clock starts with the correct second, but doesn't keep updating real time - the clock is stuck.

Any idea?

about 4 years ago · Juan Pablo Isaza
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