use-interval-react-lite
v1.0.0
Published
Declarative React 18 & 19 interval and timeout hooks with dynamic delay, pause, resume, and immediate execution.
Maintainers
Readme
use-interval-react-lite
Declarative React 18 & 19 interval and timeout hooks with dynamic delay, pause, resume, and immediate execution support.
Why use-interval-react-lite?
Using setInterval natively inside React's useEffect is infamous for causing bugs:
- Stale Closures: If your callback captures state or props, it gets frozen at the moment the interval was created unless listed in dependencies. Adding dependencies frequently clears and restarts the interval, resetting your timer cycle.
- Missing Controls: Pausing, resuming, or resetting a standard interval requires cumbersome boolean state flags and manual ref tracking.
- Delayed First Execution: Standard intervals wait until the first full duration completes before running for the first time.
- React 18 & 19 Strict Mode Double Mounts: Can easily spawn zombie intervals if cleanup handlers aren't meticulously crafted.
use-interval-react-lite solves this declaratively:
- No Stale Closures: Internally saves your callback in a ref, allowing your function to always access the freshest state without restarting the timer.
- Dynamic Controls: Out of the box
pause(),resume(),reset(), andisActiveboolean. - Dynamic Delay & Pausing: Set
delayMstonullor callpause()to effortlessly suspend ticking. - Immediate Execution: Support for
{ immediate: true }to invoke the callback right away on mount or resume. - Bonus
useTimeout: Declarative timeout hook withclear()andreset()helpers. - Zero Runtime Dependencies: Ultra-lightweight (<600 bytes minified & gzipped).
Installation
Install using your preferred package manager:
# npm
npm install use-interval-react-lite
# pnpm
pnpm add use-interval-react-lite
# yarn
yarn add use-interval-react-lite
# bun
bun add use-interval-react-liteQuick Start
import React, { useState } from 'react';
import { useInterval } from 'use-interval-react-lite';
export function Counter() {
const [count, setCount] = useState(0);
// Increments every 1000ms. Always has access to latest state!
const { pause, resume, reset, isActive } = useInterval(() => {
setCount((prev) => prev + 1);
}, 1000);
return (
<div>
<h2>Count: {count}</h2>
<p>Status: {isActive ? 'Running' : 'Paused'}</p>
<button onClick={pause}>Pause</button>
<button onClick={resume}>Resume</button>
<button onClick={reset}>Reset Timer Cycle</button>
</div>
);
}Real-World Examples
Example 1: Polling an API with Dynamic Frequency
Easily switch between fast polling when active and slow polling when idle, or pause entirely:
import React, { useState } from 'react';
import { useInterval } from 'use-interval-react-lite';
export function LiveStockTicker({ symbol }: { symbol: string }) {
const [price, setPrice] = useState<number | null>(null);
const [pollingRate, setPollingRate] = useState<number | null>(3000); // 3 seconds
const fetchPrice = async () => {
const res = await fetch(`/api/stocks/${symbol}`);
const data = await res.json();
setPrice(data.price);
};
// Run fetchPrice immediately on start, then every pollingRate ms
useInterval(fetchPrice, pollingRate, { immediate: true });
return (
<div>
<h3>{symbol}: {price ? `$${price.toFixed(2)}` : 'Loading...'}</h3>
<div>
<button onClick={() => setPollingRate(1000)}>High Speed (1s)</button>
<button onClick={() => setPollingRate(5000)}>Normal (5s)</button>
<button onClick={() => setPollingRate(null)}>Stop Polling</button>
</div>
</div>
);
}Example 2: Interactive Stopwatch with Pause & Resume
Build complete stopwatch or countdown components with declarative controls:
import React, { useState } from 'react';
import { useInterval } from 'use-interval-react-lite';
export function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const { pause, resume, reset, isActive } = useInterval(
() => setSeconds((s) => s + 1),
1000
);
const handleFullReset = () => {
reset();
setSeconds(0);
};
return (
<div className="stopwatch">
<h1>{seconds}s</h1>
<button onClick={isActive ? pause : resume}>
{isActive ? 'Pause' : 'Resume'}
</button>
<button onClick={handleFullReset}>Reset</button>
</div>
);
}Example 3: Auto-Dismiss Toast Alert with useTimeout
Dismiss flash banners automatically after a preset duration, with ability to hover and cancel:
import React, { useState } from 'react';
import { useTimeout } from 'use-interval-react-lite';
export function ToastMessage({ message, onDismiss }: { message: string; onDismiss: () => void }) {
const [delay, setDelay] = useState<number | null>(4000); // 4 seconds
const { clear, reset } = useTimeout(() => {
onDismiss();
}, delay);
return (
<div
className="toast-alert"
onMouseEnter={clear} // pause timeout when user hovers
onMouseLeave={reset} // restart countdown when user leaves
>
<span>{message}</span>
<button onClick={onDismiss}>×</button>
</div>
);
}API Reference
useInterval(callback, delayMs, options?)
| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| callback | () => void | required | Function called on each interval tick |
| delayMs | number \| null | required | Interval duration in milliseconds. Pass null to suspend. |
| options.immediate| boolean | false | When true, fires callback immediately on mount / resume |
Returns IntervalControls:
pause: () => void- Suspends the running interval without clearing state.resume: () => void- Resumes the interval if paused.reset: () => void- Resets and restarts the interval clock cycle.isActive: boolean- True if currently running and ticking.
useTimeout(callback, delayMs)
| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| callback | () => void | required | Function executed after timeout completes |
| delayMs | number \| null | required | Delay in milliseconds, or null to disable |
Returns TimeoutControls:
reset: () => void- Restarts the timeout timer.clear: () => void- Cancels the pending timeout.isPending: boolean- True if the timer is currently waiting to fire.
TypeScript Types
export interface UseIntervalOptions {
immediate?: boolean;
}
export interface IntervalControls {
pause: () => void;
resume: () => void;
reset: () => void;
isActive: boolean;
}
export interface TimeoutControls {
reset: () => void;
clear: () => void;
isPending: boolean;
}Contributing
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
License
MIT © Pirapaakaran Pirathapan
Support & Sponsor
If you find this hook useful in your React projects, please consider supporting my open-source work:
