Last active
November 12, 2025 19:37
-
-
Save isocroft/42b68a5ffc1ddbe80655887d385d789c to your computer and use it in GitHub Desktop.
A simple hook that updates the current time in ReactJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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