Created
April 17, 2024 14:50
-
-
Save officialdavidtaylor/c26b11fcc25550f48252132f433d04f3 to your computer and use it in GitHub Desktop.
A React Custom Hook to opt the component (and all downstream components) into re-renders that occur on a specified interval.
This file contains 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 { useRef, useState } from 'react'; | |
/** | |
* This hook will opt your component (and all downstream components) into | |
* rerenders that occur on the interval specified. | |
* | |
* ⚠️ This may induce serious performance consequences, especially when | |
* choosing a shorter intervalDuration | |
* | |
* @param intervalDuration number (in ms), default to 1000ms | |
* @returns the number of ms since Jan 1, 1970 (UTC) | |
*/ | |
export function useCurrentTime(intervalDuration: number = 1000) { | |
const isInitialized = useRef(false); | |
const [currentTime, setCurrentTime] = useState(Date.now); | |
if (!isInitialized.current) { | |
setInterval(() => { | |
setCurrentTime(Date.now); | |
}, intervalDuration); | |
isInitialized.current = true; | |
} | |
return currentTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment