icns-frontend/hooks/use-interval.tsx
2022-12-21 22:39:07 +09:00

27 lines
708 B
TypeScript

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;