Nice beginner article @yuridevat and great comment @lukeshiru . I also would rather store the unix timespan than the values individually, it makes easier to do math with it and you wouldn't need even to setTime a new timespan every second, a simple subtraction would do the trick. =D
Building on that, here's a handy hook:
import{useState,useEffect}from"react";constSECOND=1_000;constMINUTE=SECOND*60;constHOUR=MINUTE*60;constDAY=HOUR*24;exportdefaultfunctionuseTimer(deadline,interval=SECOND){const[timespan,setTimespan]=useState(newDate(deadline)-Date.now());useEffect(()=>{constintervalId=setInterval(()=>{setTimespan((_timespan)=>_timespan-interval);},interval);return()=>{clearInterval(intervalId);};},[interval]);/* If the initial deadline value changes */useEffect(()=>{setTimespan(newDate(deadline)-Date.now());},[deadline]);return{days:Math.floor(timespan/DAY),hours:Math.floor((timespan/HOUR)%24),minutes:Math.floor((timespan/MINUTE)%60),seconds:Math.floor((timespan/SECOND)%60)};}
Nice beginner article @yuridevat and great comment @lukeshiru . I also would rather store the unix timespan than the values individually, it makes easier to do math with it and you wouldn't need even to
setTime
a new timespan every second, a simple subtraction would do the trick. =DBuilding on that, here's a handy hook:
Then its simple to use: