portfolio articles contact

nate levin

React Hook: useCurrentTime

React Hook: useCurrentTime graphic

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().

Talk about this article on Github


Read more like this

Connect with me