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

219
Visualizações
Why is my console printing the same date and not updating like the html

This is my first question on stackoverflow. I am currently learning react and I tried to make a live clock which updates every second. I managed to accomplish the html updating through a useState() hook and a useEffect() hook. Now, I tried printing the current time into the Console when it updates but the console only shows the time when the site was refreshed the last time.

Result: HTML keeps updating correctly but the console stays on the same time.

Could someone explain to me what I am doing wrong or what is the cause to this bug?

Clock.js:

import { render } from "@testing-library/react";
import React, { useState, useEffect } from 'react';

function Clock() {
    const [dateState, setDateState] = useState(new Date());

    function updateFunc(){
        setDateState(new Date());
        console.log(dateState.toLocaleString('eu-DE', {
            second: 'numeric',
            minute: 'numeric',
            hour: 'numeric',
         }));
        
    }

    useEffect(() => {
           setInterval(() => updateFunc(), 1000);
    }, []);
    return (
        <div className="App">
            <p>
              {' '}
              {dateState.toLocaleDateString('eu-DE', {
                 day: 'numeric',
                 month: 'short',
                 year: 'numeric',
              })}
            </p>
            <p>
             {dateState.toLocaleString('eu-DE', {
                hour: 'numeric',
                minute: 'numeric',
                second: 'numeric',
                hour12: false,
            })}
            </p>
        </div>
    );
}    

  export default Clock;
  
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If I'm not mistaking, since the useEffect has no dependencies, the callback never changes. The callback has its own scope and the variables (dateState) that's why it never changes.

If you pass an empty array ([]), the props and state inside the effect will always have their initial values

source

The solution is to add updateFunc to the useEffect dependencies list. Then you will need to wrap updateFunc with useCallback with dateState as a dependency.

Note: When the component subscribes to an endless handler (e.g. setInterval or socket) it's better to unsubscribe using the cleanup function.

function Clock() {
  const [dateState, setDateState] = useState(new Date());

  const updateFunc = useCallback(() => {
    setDateState(new Date());
    console.log(
      dateState.toLocaleString("eu-DE", {
        second: "numeric",
        minute: "numeric",
        hour: "numeric"
      })
    );
  }, [dateState]);

  useEffect(() => {
    const interval = setInterval(() => updateFunc(), 1000);
    return () => clearInterval(interval);
  }, [updateFunc]);

  return (
    <div className="App">
      <p>
        {" "}
        {dateState.toLocaleDateString("eu-DE", {
          day: "numeric",
          month: "short",
          year: "numeric"
        })}
      </p>
      <p>
        {dateState.toLocaleString("eu-DE", {
          hour: "numeric",
          minute: "numeric",
          second: "numeric",
          hour12: false
        })}
      </p>
    </div>
  );
}

https://codesandbox.io/s/stackoverflow-70423606-4umr2

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