Skip to content

Instantly share code, notes, and snippets.

@officialdavidtaylor
Created April 17, 2024 14:50
Show Gist options
  • Save officialdavidtaylor/c26b11fcc25550f48252132f433d04f3 to your computer and use it in GitHub Desktop.
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.
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