Created
April 4, 2022 18:27
-
-
Save MrDesjardins/76486b98ed8b590bd2bd053a65be23f8 to your computer and use it in GitHub Desktop.
React useInterval
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 { useEffect, useRef } from "react"; | |
export interface useIntervalProps { | |
callback: () => void; | |
intervalMs: number; | |
/** | |
* Option to have an initial call to the callback immediately once the hook is created and | |
* then at each interval. When not defined or false, the first callback call is delayed until | |
* the interval has passed. | |
**/ | |
immediate?: boolean; | |
} | |
/** | |
* Original code https://overreacted.io/making-setinterval-declarative-with-react-hooks/#extracting-a-hook | |
* Modified to handle options and to be in TypeScript | |
**/ | |
export function useInterval(props: useIntervalProps): void { | |
const savedCallback = useRef<() => void>(); | |
useEffect(() => { | |
savedCallback.current = props.callback; | |
}); | |
useEffect(() => { | |
if (props.immediate) { | |
savedCallback?.current?.(); | |
} | |
}, [props.immediate]); | |
useEffect(() => { | |
function tick() { | |
savedCallback?.current?.(); | |
} | |
const id = window.setInterval(tick, props.intervalMs); | |
return () => window.clearInterval(id); | |
}, [props.intervalMs]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment