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
optionsis a number type,enableddefaults totrue.
Returns set, reset, and clear functions for direct interval control.
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
| Name | Type | Description |
|---|---|---|
callback | () => void | Callback function to execute on each interval |
options | number | IntervalOptions | Interval delay in milliseconds or a { delay: number; enabled?: boolean } options object |
Options
| Name | Type | Default | Description |
|---|---|---|---|
delay | number | - | Interval delay in milliseconds |
enabled | boolean | true | Whether the interval runs automatically |
Returns
| Name | Type | Description |
|---|---|---|
set | () => void | Starts the interval |
clear | () => void | Clears the interval |
reset | () => void | Resets 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