Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
React useEffect default value does not update properly

I am getting the property endDate from a redux store and I am sure that the property is not null or undefined, but then again the state keeps it's previous displayed value until the page is refreshed. I want the page to automatically set the state of timeLeft to millisecondsToTime(now, endDate) by default, but currently it fails, despite working after reload.

import React, { FC, useEffect, useState } from "react";
import { millisecondsToTime } from "src/utils/helpers";

import {
  StyledCountdownTimer,
  StyledTimeBox,
  StyledTimeBoxNumbers,
  StyledTimeBoxText
} from "./StyledCountdownTimer";
import { getActiveCampaign } from "../../reduxStore";

export interface CountdownTimerProps {
  endDate?: string;
}

const CountdownTimer: FC<CountdownTimerProps> = ({ endDate }) => {
  const now = Date.now();
  const [timeLeft, setTimeLeft] = useState(millisecondsToTime(now, endDate));

  const data = getActiveCampaign();

  console.log(data);

  useEffect(() => {
    const timer = setTimeout(() => {
      setTimeLeft(millisecondsToTime(now, endDate));
    }, 1000);

    if (timeLeft.finished) {
      clearTimeout(timer);
    }

    return () => {
      clearTimeout(timer);
    };
  }, [endDate, now, timeLeft.finished]);

  return (
    <StyledCountdownTimer>
      {endDate}
      {timeLeft.days}
      {millisecondsToTime(now, endDate).days}
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.days}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Days</StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.hours}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Hours</StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.minutes}</StyledTimeBoxNumbers>
        <StyledTimeBoxText></StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.seconds}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Seconds</StyledTimeBoxText>
      </StyledTimeBox>
    </StyledCountdownTimer>
  );
};

export { CountdownTimer };
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!