how to implement a react countdown using a single useState hook?
i am trying to make a countdown in the format 00:00.
i am able to implement it with using two useState , however i want to make it using a single useState
const [counter, setCounter] = React.useState([12, 0]); React.useEffect(() => { const timer = counter > 0 && setInterval(() => { setCounter([counter[0] - 1,Math.floor((counter[1] % 3600) / 60)]); }, 1000); return () => clearInterval(timer); }, [counter]);
Answer
You should store your counter just as seconds/minutes. When you render it you can convert it to, for example, MM:SS format using something like this:
function secondsToMMSS(seconds) { var m = Math.floor(seconds / 60); var s = seconds % 60; return (m < 10 ? '0' : '') + m + ":" + ('0' + s).slice(-2); }