Skip to main content

useInterval

A custom hook for conveniently using window.setInterval.

The second argument options can be either a number or an object of type { delay: SetIntervalParameters[1]; enabled?: boolean }.

If options is a number, that value becomes the delay for setInterval. If it is an object, you can additionally control whether setInterval runs via the enabled option.

  • 💡 When options is a number type, enabled defaults to true.

Returns set, reset, and clear functions for direct interval control.


Code

🔗 View source code


Interface

typescript
interface IntervalOptions {
delay: number;
enabled?: boolean;
}
typescript
// Function overloads
function useInterval(
callback: () => void,
options: number
): {
set: () => void;
clear: () => void;
reset: () => void;
};

function useInterval(
callback: () => void,
options: IntervalOptions
): {
set: () => void;
clear: () => void;
reset: () => void;
};

Parameters

NameTypeDescription
callback() => voidCallback function to execute on each interval
optionsnumber | IntervalOptionsInterval delay in milliseconds or a { delay: number; enabled?: boolean } options object

Options

NameTypeDefaultDescription
delaynumber-Interval delay in milliseconds
enabledbooleantrueWhether the interval runs automatically

Returns

NameTypeDescription
set() => voidStarts the interval
clear() => voidClears the interval
reset() => voidResets the interval (clears and restarts)

Usage

typescript
import { useInterval } from '@modern-kit/react';

const Example = () => {
const [number, setNumber] = useState(0);

const { set, clear, reset } = useInterval(
() => setNumber(number + 1),
{ delay: 1000, enabled: false } // does not auto-start
);

/*
* useInterval(() => {
* setNumber(number + 1);
* }, 1000); // auto-starts
*/

return (
<div>
<p>{number}</p>
<button onClick={set}>set</button>
<button onClick={clear}>clear</button>
<button onClick={reset}>reset</button>
</div>
);
};

Example

Count: 0