useInterval
A declarative interval hook based on Dan Abramov’s article on overreacted.io. The interval can be paused by setting the delay to null
You can also manually control it by passing the controls parameter.
useInterval wraps setInterval in a declarative React API. It takes a callback, a delay in milliseconds (or null to pause), and an optional options object. It returns a Pausable object with isActive, pause, and resume methods for manual control. The callback always references the latest closure without resetting the interval.
When to Use
- Building countdown timers, clocks, or polling mechanisms that tick at a regular interval
- Auto-refreshing data from an API at a fixed cadence
- Animating values over time with a consistent step interval
Notes
- Pause/resume: Set
delaytonullto pause the interval, or use the returnedpause()/resume()methods for imperative control. - Immediate option: Pass
{ immediate: true }to execute the callback immediately on start in addition to after each interval. - The interval is automatically cleared on component unmount. See also
useTimeoutfor single-fire delayed execution anduseRafFnfor frame-based animation loops.
Usage
Live Editor
function Demo() { const [count, setCount] = useState(0); useInterval(() => { setCount(count + 1); }, 1000); return <div>count: {count}</div>; };
Result
API
useInterval
Returns
Pausable
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| callback | callback | () => void (Required) | - |
| delay | Time, if null then stop the timer | number | null | undefined | - |
| options | optional params | UseIntervalOptions | undefined | - |
UseIntervalOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| immediate | Whether to execute immediately. | boolean | - |
| controls | Whether to control execution. | boolean | - |
Pausable
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| isActive | A ref indicate whether a pausable instance is active | RefObject<boolean> (Required) | - |
| pause | Temporary pause the effect from executing | () => void (Required) | - |
| resume | Resume the effects | () => void (Required) | - |