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);
}
}, []);
CodePudding user response:
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.
CodePudding user response:
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);
}, []);