DEV Community

Discussion on: How To Create A Timer With React

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

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";

const SECOND = 1_000;
const MINUTE = SECOND * 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;

export default function useTimer(deadline, interval = SECOND) {
  const [timespan, setTimespan] = useState(new Date(deadline) - Date.now());

  useEffect(() => {
    const intervalId = setInterval(() => {
      setTimespan((_timespan) => _timespan - interval);
    }, interval);

    return () => {
      clearInterval(intervalId);
    };
  }, [interval]);

  /* If the initial deadline value changes */
  useEffect(() => {
    setTimespan(new Date(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)
  };
}
Enter fullscreen mode Exit fullscreen mode

Then its simple to use:

const { days, hours, minutes, seconds } = useTimer("2022-12-31T23:59:59");
Enter fullscreen mode Exit fullscreen mode