skip to Main Content

I am trying to create a countdown timer using useEffect hook and setInterval function, but it is not ever executing the code when the timer reaches 0. Also, when I console.log the value of the countdown variable it doesn’t decrement.


  // set up counter for (un)flipped phone countdown
  // countdown of 20 seconds
  const [countdown, setCountdown] = useState(20);
  let intervalID: any;

  // on initialize
  useEffect(() => {
    // every second reduce countdown by 1
    intervalID = setInterval(() => {
      setCountdown(countdown - 1);
    }, 1000);

    return () => clearInterval(intervalID);
  }, []);

  // check if countdown has reached 0
  useEffect(() => {
    if (countdown == 0) {
      timerReset();
      alert("TIMER RESET");
      clearInterval(intervalID);
    }
  }, []);

2

Answers


  1. The code in the body of your component functions runs in every render. Which means you are setting interval id to undefined on every render. Use useRef to store the value instead.

    And your second effect shouldn’t be a mount effect, it needs to have count down as a dependency. Make sure to read all the docs on useEffect.

    Login or Signup to reply.
  2. You can try this :

    const [countdown, setCountdown] = useState(20);
    
    useEffect(() => {
      let intervalID = setInterval(() => {
        setCountdown(prev => {
          if (prev === 0) clearInterval(intervalID);   // handle the condition here
          return prev - 1;
        });
      }, 1000);
      return () => clearInterval(intervalID);
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search