Use Interval

A hook that executes a callback function at specified delays using the useInterval API.

Preview

Installation

CLI

npx shadcn@latest add https://kelvinmai.io/r/use-interval.json

Manual

Copy and paste the following code into your project

hooks/use-interval.ts
'use client';
import * as React from 'react';
export const useInterval = (callback: () => void, delay: number | null) => {
const ref = React.useRef(callback);
React.useEffect(() => {
ref.current = callback;
}, [callback]);
React.useEffect(() => {
if (delay === null || typeof delay !== 'number') {
return;
}
const tick = () => ref.current();
const id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
};

Update the import paths to match your project setup

Usage

import { useInterval } from '@/hooks/use-interval';
useInterval(() => {
func();
}, 1000);

API Reference

Parameters

NameTypeDescription
callback
() => void
The function to be invoked at each interval.
delay
number | null
The interval time in milliseconds between each callback invocation. Use null to clear the interval.