27 lines
708 B
TypeScript
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;
|