@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
43 lines (40 loc) • 970 B
JavaScript
'use client';
import { useState, useRef, useEffect } from 'react';
function useInterval(fn, interval, { autoInvoke = false } = {}) {
const [active, setActive] = useState(false);
const intervalRef = useRef();
const fnRef = useRef();
const start = () => {
setActive((old) => {
if (!old && !intervalRef.current) {
intervalRef.current = window.setInterval(fnRef.current, interval);
}
return true;
});
};
const stop = () => {
setActive(false);
window.clearInterval(intervalRef.current);
intervalRef.current = void 0;
};
const toggle = () => {
if (active) {
stop();
} else {
start();
}
};
useEffect(() => {
fnRef.current = fn;
active && start();
return stop;
}, [fn, active, interval]);
useEffect(() => {
if (autoInvoke) {
start();
}
}, []);
return { start, stop, toggle, active };
}
export { useInterval };
//# sourceMappingURL=use-interval.mjs.map