UNPKG

qol-hooks

Version:

A collection of React hooks to improve the quality of life of developers.

28 lines (27 loc) 932 B
import { useEffect, useRef } from "react"; /** * @description A hook to call a function at a specified interval * @param {() => void} callback The function to call at the specified interval * @param {number | null | undefined} delay The delay in milliseconds * * @example```tsx * useInterval(() => console.log("Hello, World!"), 1000); // Logs "Hello, World!" every second * ``` */ function useInterval(callback, delay) { const savedCallback = useRef(); useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { function tick() { var _a; (_a = savedCallback.current) === null || _a === void 0 ? void 0 : _a.call(savedCallback); } if (delay !== null && delay !== undefined) { const id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); } export default useInterval;