I'm trying to implement the countdown timer with React's hooks. I knew, we have couple of solutions out there and thanks for that. My question is NOT How to implement timer with React's hooks
BUT What is the problem with my approach
Here is my code so far.
import React, { useEffect, useState } from "react";
const Timer = () => {
const [minutes, setMinutes] = useState(29);
const [seconds, setSeconds] = useState(59);
useEffect(() => {
const secondInterval = setInterval(() => {
setSeconds((prev) => (prev - 1 < 0 ? 59 : prev - 1));
}, 1000);
const minuteInterval = setInterval(() => {
setMinutes(minutes - 1);
}, 60000);
return () => {
clearInterval(secondInterval);
clearInterval(minuteInterval);
};
});
return (
<div>
{minutes === 0 && seconds === 0 ? null : (
<h1>
{" "}
{minutes}:{seconds < 10 ? `0${seconds}` : seconds}
</h1>
)}
</div>
);
};
export default Timer;
Basically, I just set 2 interval for every render with useEffect
no depths. But the second setTimeInterval
does not run and the minutes show 29
everytime.
Thanks in advance !