Skip to content

useInterval

Tracks the idle state of an user.

Installation

npx rabbithook@latest add use-interval

Usage

App.tsx
import useInterval from "@/hooks/use-interval";
function Component() {
useInterval(() => {
console.log("Executed every 15 seconds");
}, 15 * 1000 /* 15 seconds */);
return ();
}

Code

use-interval.ts
import { useEffect, useRef } from "react"
type UseIntervalOptions = {
immediate: boolean
startPaused: boolean
}
function useInterval<T extends () => void>(
callback: T,
delay: number,
{ immediate, startPaused }: Partial<UseIntervalOptions> = { immediate: false, startPaused: false }
) {
const savedCallback = useRef(callback);
const tickId = useRef<NodeJS.Timeout>();
function start() {
if (!tickId.current) {
tickId.current = setInterval(() => savedCallback.current(), delay);
}
}
function stop() {
if (tickId.current) {
clearInterval(tickId.current);
tickId.current = undefined;
}
}
useEffect(() => {
savedCallback.current = callback;
if (immediate) {
callback();
}
}, [callback, immediate])
useEffect(() => {
if (!tickId.current && startPaused) {
return;
}
start();
return stop;
}, [delay, startPaused])
return {
startTimer: start,
stopTimer: stop,
}
}
export default useInterval;