Skip to content

Instantly share code, notes, and snippets.

@pomle
Created February 14, 2020 06:32
Show Gist options
  • Save pomle/8dae53c57ed0a1e51fe95675aab81743 to your computer and use it in GitHub Desktop.
Save pomle/8dae53c57ed0a1e51fe95675aab81743 to your computer and use it in GitHub Desktop.
import { useState, useEffect, useMemo } from "react";
import moment, { Moment, DurationInputArg2 as Unit } from "moment";
export const useLiveTime = (unit: Unit): Moment => {
const initial = useMemo(moment, []);
const [time, setTime] = useState<Moment>(initial);
useEffect(() => {
const nextTime = time
.clone()
.startOf(unit)
.add(1, unit);
const delay = nextTime.diff(time, "milliseconds");
const timer = setTimeout(setTime, delay, nextTime);
return () => clearTimeout(timer);
}, [unit, time, setTime]);
return time;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment