icns-frontend/hooks/use-interval.tsx

27 lines
708 B
TypeScript
Raw Normal View History

2022-12-21 13:39:07 +00:00
import { useEffect, useRef } from "react";
import useIsomorphicLayoutEffect from "./use-isomorphic-layout-effect";
function useInterval(callback: () => void, delay: number | null) {
const savedCallback = useRef(callback);
// Remember the latest callback if it changes.
useIsomorphicLayoutEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
// Don't schedule if no delay is specified.
// Note: 0 is a valid value for delay.
if (!delay && delay !== 0) {
return;
}
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
export default useInterval;