Skip to content

Instantly share code, notes, and snippets.

@isocroft
Last active November 12, 2025 19:37
Show Gist options
  • Select an option

  • Save isocroft/42b68a5ffc1ddbe80655887d385d789c to your computer and use it in GitHub Desktop.

Select an option

Save isocroft/42b68a5ffc1ddbe80655887d385d789c to your computer and use it in GitHub Desktop.
A simple hook that updates the current time in ReactJS
import moment from 'moment'
import { useState, useEffect } from 'react'
export const useCurrentTime = (formatting = 'hh:mm A', intervalDuration = (1000 * 60)) => {
const [currentTime, setCurrentTime] = useState(() => moment().format(formatting))
useEffect(() => {
const updateTime = () => {
setCurrentTime(moment().format(formatting))
}
let interval = null;
if (interval === null) {
/* @HINT: Update time immediately on mount */
updateTime();
}
/* @NOTE: Default is to update the time every minute */
interval = setInterval(updateTime, intervalDuration)
return () => {
clearInterval(interval);
}
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [formatting, intervalDuration])
return currentTime;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment