Skip to content

Instantly share code, notes, and snippets.

@MrDesjardins
Created April 4, 2022 18:27
Show Gist options
  • Save MrDesjardins/76486b98ed8b590bd2bd053a65be23f8 to your computer and use it in GitHub Desktop.
Save MrDesjardins/76486b98ed8b590bd2bd053a65be23f8 to your computer and use it in GitHub Desktop.
React useInterval
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