Let's assume that we want to create a timer in React that refreshes every second and displays the countdown in hh:mm:ss
format.
The goal is to create a component like that:
jsx<Timer end = '20/09/2025 23:00'/>
Here is an example on how to calculate the difference between 2 dates in hh:mm:ss
format:
javascript// Defining current moment and end date let now = moment(); let end = moment('20/09/2025 23:00', 'DD/MM/YYYY hh:mm'); // Getting the difference in hours, minutes and seconds let h = end.diff(now, 'hours'); let m = end.diff(now, 'minutes') - (60 * h); let s = end.diff(now, 'seconds') - (60 * 60 * h) - (60 * m); // Adding a zero in the left if the number is < 10 let hh = ('0' + h).slice(-2); let mm = ('0' + m).slice(-2); let ss = ('0' + s).slice(-2);
To perceive the effect of seconds going down, we need to recalculate the function every second. Now it's turn for React.
We'll trigger the useEffect()
every second using the setTimeout()
function:
jsximport React, { useEffect, useState } from 'react'; import moment from 'moment'; const Timer = (props) => { const [HH, setHH] = useState(null); const [MM, setMM] = useState(null); const [SS, setSS] = useState(null); useEffect(() => { let now = moment(); let end = moment(props.end, 'DD/MM/YYYY hh:mm'); let h = end.diff(now, 'hours'); let m = end.diff(now, 'minutes') - (60 * h); let s = end.diff(now, 'seconds') - (60 * 60 * h) - (60 * m); let hh = ('0' + h).slice(-2); let mm = ('0' + m).slice(-2); let ss = ('0' + s).slice(-2); setTimeout(() => { setHH(hh); setMM(mm); setSS(ss); }, 1000); }, [SS]); return( <React.Fragment> {`${HH}:${MM}:${SS}`} </React.Fragment> ); } export default Timer;
Live example at CodePen.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.