UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

54 lines (53 loc) 1.43 kB
"use client"; import { useCallback, useEffect, useRef, useState } from "react"; //#region packages/@mantine/hooks/src/use-interval/use-interval.ts function useInterval(fn, interval, { autoInvoke = false } = {}) { const [active, setActive] = useState(false); const intervalRef = useRef(null); const fnRef = useRef(null); const intervalValueRef = useRef(interval); intervalValueRef.current = interval; const start = useCallback(() => { setActive((old) => { if (!old && !intervalRef.current) intervalRef.current = window.setInterval(fnRef.current, intervalValueRef.current); return true; }); }, []); const stop = useCallback(() => { setActive(false); if (intervalRef.current) window.clearInterval(intervalRef.current); intervalRef.current = null; }, []); const toggle = useCallback(() => { setActive((current) => { if (current) { if (intervalRef.current) window.clearInterval(intervalRef.current); intervalRef.current = null; return false; } if (!intervalRef.current) intervalRef.current = window.setInterval(fnRef.current, intervalValueRef.current); return true; }); }, []); useEffect(() => { fnRef.current = fn; active && start(); return stop; }, [ fn, active, interval ]); useEffect(() => { if (autoInvoke) start(); }, []); return { start, stop, toggle, active }; } //#endregion export { useInterval }; //# sourceMappingURL=use-interval.mjs.map