I'm building a component that renders the elapsed time from a given date. The date is a timestamp, for example, 1600836722.
Here is what I have so far:
const FORMAT_PATTERN = "DD/MM/YYYY HH:mm:ss"; export default function Timer({ dateCreated }) { const [hours, setHours] = useState(0); const [minutes, setMinutes] = useState(0); const [seconds, setSeconds] = useState(0); const [startTime, setStartTime] = useState(); useEffect(() => { const orderTimestamp = Moment.unix(dateCreated); setStartTime(Moment(orderTimestamp, FORMAT_PATTERN)); }, [dateCreated]); useEffect(() => { let interval = null; interval = setInterval(() => { const now = Moment(Date.now()); const difference = Moment.duration( Moment(now, FORMAT_PATTERN).diff(startTime) ); setHours(Math.floor(difference.asHours())); // this is so that 1 day, 12 hours will be 34 hours setMinutes(Moment.utc(now.diff(startTime)).format("mm")); setSeconds(Moment.utc(now.diff(startTime)).format("ss")); }, 1000); return () => clearInterval(interval); }, [hours, minutes, seconds]); return hours && seconds && minutes ? ( <Typography>{[hours, minutes, seconds].join(":")}</Typography> ) : null; } It works, displays the time just fine but there will be multiple components on the same page that track the elapsed time and my approach does not seem the most optimized. Any ideas?