React Hook: useCurrentTime
Here is a neat little TypeScript React hook I created today that returns a live-updating Date
representing the current time.
function useCurrentTime(msBetweenUpdates: number = 1_000) {
const [curTime, setCurTime] = useState(new Date());
useEffect(() => {
const intervalId = setInterval(() => {
setCurTime(new Date());
}, msBetweenUpdates);
return () => clearInterval(intervalId);
}, [msBetweenUpdates]);
return curTime;
}
Usage examples:
// updated every second
const curTime = useCurrentTime();
// updated every 30 seconds
const delayedTime = useCurrentTime(30 * 1_000);
It will cause your component to re-render — if you don't want this behavior, just set a variable equal to new Date()
.