useInterval
A declarative React hook for setInterval with pause/resume support.
Overview
useInterval provides a declarative way to use setInterval in React. Unlike the imperative setInterval, this hook handles cleanup automatically and allows pausing by passing null as the delay.
Demo
API Reference
function useInterval(callback: () => void, delay: number | null): voidParameters
| Name | Type | Description |
|---|---|---|
callback | () => void | Function to call on each interval. |
delay | number | null | Interval delay in milliseconds. Pass null to pause. |
Usage Examples
Basic Timer
import { useInterval } from 'react-hooks-ts'
function Timer() {
const [seconds, setSeconds] = useState(0)
useInterval(() => {
setSeconds(s => s + 1)
}, 1000)
return <div>{seconds}s</div>
}Pausable Counter
import { useInterval } from 'react-hooks-ts'
function PausableCounter() {
const [count, setCount] = useState(0)
const [isRunning, setIsRunning] = useState(true)
useInterval(() => {
setCount(c => c + 1)
}, isRunning ? 1000 : null) // null = paused
return (
<div>
<p>{count}</p>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? 'Pause' : 'Resume'}
</button>
</div>
)
}Polling API
import { useInterval } from 'react-hooks-ts'
function LiveData() {
const [data, setData] = useState(null)
useInterval(async () => {
const response = await fetch('/api/data')
setData(await response.json())
}, 5000) // Poll every 5 seconds
return <DataDisplay data={data} />
}Features
- ⏱️ Declarative - No manual cleanup needed.
- ⏸️ Pausable - Pass
nullto stop the interval. - 🔄 Dynamic Delay - Change interval timing on the fly.
- 🧹 Auto Cleanup - Clears interval on unmount.