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

138
Visualizações
useEffect not updating variables on function call

I have a component called Date with three variables. I also have a function called setCurrentTimes that is supposed to update the variables each time it is called with the current values.

I call the function inside react's useEffect that has no dependencies to update the variables on the component mount.

Here is the date component.

const Date = () => {
  var currentDate;
  var currentTime;
  var amOrPm;

  const setCurrentTimes = () => {
    currentDate = moment().format("d MMMM YYYY");
    currentTime = moment().format(" h:mm:ss ");
    amOrPm = moment().format("a");
  };

  useEffect(() => {
    setCurrentTimes();
  }, []);

  return (
    <div className="Date flex__container-v">
      {amOrPm === "pm" ? (
        <div className="Moon__icon flex__container">
          <img src={Assets.Moon} alt="Moon Icon" />
          <p className="p__poppins Date__greeting">Good Evening</p>
        </div>
      ) : (
        <div className="Sun__icon flex__container">
          <img src={Assets.Sun} alt="Sun Icon" />
          <p className="p__poppins Date__greeting">Good Morning</p>
        </div>
      )}
      <div className="Date__btm flex__container">
        <p className="p__poppins">{currentDate}</p>
        <p className="p__poppins">{currentTime}</p>
      </div>
    </div>
  );
};

The component returns different things depending on the variables. However, it is not working as expected. When I try to log out the variables inside the return statement I get undefined.

I don't get what I am doing wrong.

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

0

Short answer: use state in order to fix this.

Longer answer:

You are probably expecting useEffect to run before render, but this is not the case.

useEffect is always called after the render phase of the component. Your ParentComponent consists of Input, Input & ChildComponent.

In your case you are trying to display variables that are not yet set. If you were to use State instead of variables your UI would re-render after setting these states. Since you're using variables your UI wont re-render causing it to always display the initial values (which is empty).

simplified example:

const Date = () => {

    const [currentDate,setCurrentDate] = React.useState();

    useEffect(() => {
      setCurrentDate(moment().format("d MMMM YYYY"));
    }, []);
  
    return (
      <div className="Date flex__container-v">
        <div className="Date__btm flex__container">
          <p className="p__poppins">{currentDate}</p>
        </div>
      </div>
    );
  };
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