Repository URL to install this package:
|
Version:
0.0.0 ▾
|
import { useEffect, useRef } from 'react';
export function useInterval(callback, delay, leading = true) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
const current = savedCallback.current;
current && current();
}
if (delay !== null) {
if (leading)
tick();
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
return undefined;
}, [delay, leading]);
}