useInterval
A React hook that provides a declarative way to set up intervals that are automatically cleaned up when the component unmounts, with support for dynamic delays and pausing.
Demo
1. Simple Counter
2. Stopwatch Timer
3. Progress Bar
Installation
npm install @thibault.sh/hooks
Usage
import { useInterval } from "@thibault.sh/hooks";
function Counter() {
const [count, setCount] = useState(0);
const [isRunning, setIsRunning] = useState(true);
useInterval(
() => {
setCount(count + 1);
},
isRunning ? 1000 : null
);
return (
<div>
<div>Count: {count}</div>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? "Pause" : "Resume"}
</button>
</div>
);
}
API Reference
Parameters
callback
The function to call on each interval. This function should contain any state updates or side effects you want to run periodically.
() => void
delay
The time in milliseconds between each callback invocation. Pass null to pause the interval. The delay can be changed dynamically to adjust the interval timing.
number | null
Features
Automatic Cleanup
Intervals are automatically cleared when the component unmounts or when the delay changes, preventing memory leaks and unexpected behavior.
Dynamic Control
Easily pause and resume intervals by passing null as the delay, or dynamically adjust the interval timing by changing the delay value.
Declarative API
Provides a clean, declarative way to handle intervals in React components, making code more maintainable and easier to understand.
Type Safety
Full TypeScript support ensures type safety for callback functions and delay values, catching potential errors at compile time.
Common Use Cases
Periodically fetch data from an API to keep the UI in sync with the server. The interval can be paused when the component is not visible.
Create smooth animations or transitions by updating values at a fixed interval. Perfect for progress bars, countdowns, or simple game loops.
Automatically save form data or document changes at regular intervals, with the ability to pause when no changes are detected.