DEV Community

Discussion on: How To Create A Timer With React

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him) • Edited

May I suggest a few things?

  • Date.now() would do the trick instead of Date.parse(new Date()).
  • let interval could be const interval. It's never reassigned.
  • Since you already define deadline within the scope of Timer there is no need to use it as a parameter for the getTime function.
  • I'd probably only use one state called timeDiff and use an object in the state
const getTime = () => {
    const time = new Date(deadline) - new Date();

    setTimeDelta({
        days: Math.floor(time / (1000 * 60 * 60 * 24)),
        hours: Math.floor((time / (1000 * 60 * 60)) % 24),
        minutes: Math.floor((time / 1000 / 60) % 60),
        seconds: (Math.floor((time / 1000) % 60)),
    })
};
Enter fullscreen mode Exit fullscreen mode

With React 18's Automatic Batching this is no longer that important, but I feel it's better to have less different state variables if they are always dependent.
Also this approach would make it easier to have really pure getTime function which only returns the object used to set the new state.

To repeat this function, we must clear the interval after each rendering using the clearInterval() function.

This is not entirely true: the returned function in useEffecxt is only called when the component is unmounted (or on changes in the deps, but since there are none in this case...)

Collapse
 
yuridevat profile image
Julia 👩🏻‍💻 GDE

Thank you so much for your suggestions, I will insert most of your suggestions (the ones I get 😅) right away!

Doh', I thought that I did not fully understand setInterval/clearInterval and useEffect. I will read about it again and update the information.

Thank you for helping me making this tutorial better, I really appreciate it.

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

If you have any questions feel free to reach out.