Skip to content

Instantly share code, notes, and snippets.

@utenma
Last active December 19, 2022 22:44
Show Gist options
  • Save utenma/1b31b4a56c8e5724ddcbec673e75f85d to your computer and use it in GitHub Desktop.
Save utenma/1b31b4a56c8e5724ddcbec673e75f85d to your computer and use it in GitHub Desktop.
A simple hook for managing intervals with React
import { useEffect, useRef } from 'react';
/**
* Activate with a delay greater than zero
* The last callback is applied immediately
*
* Adapted from https://usehooks-ts.com/react-hook/use-interval
*/
export function useInterval(callback: () => void, delay: number | null) {
const savedCallback = useRef(callback);
// eslint-disable-next-line no-undef
const interval = useRef<NodeJS.Timer | null>(null);
// Remember the latest callback if it changes.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
if (delay && typeof delay === 'number' && delay > 0) {
interval.current = setInterval(() => savedCallback.current(), delay);
}
// clear the interval if delay changes
return () => {
if (interval.current) clearInterval(interval.current);
};
}, [delay]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment