Skip to content

useInterval

Manage intervals conveniently using the useInterval hook.

The useInterval hook is helpful when you want to invoke a callback periodically on an interval. It can be helpful in cases when you want to peform a polling action or maybe an animation.

It automatically cleans up the interval set using the window.setInterval API when component unmounts and also returns an cancelInterval method to cancel the the interval programatically.

The hook relies on the setInterval (MDN) method available on browsers.

useInterval

Current duration is: 1000 ms

Immediate: true

Counter Value: 0

Adjust the interval period and whether to call it callback immediately using the controls.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component;

./src/App.tsx
import React from 'react';
import { useCounter, useInterval } from '@abhushanaj/react-hooks';
function App() {
const [count, { increment }] = useCounter(0);
const [cancelInterval] = useInterval(() => {
increment();
}, 1000);
return (
<div>
<p>Count: {count}</p>
<button onClick={cancelInterval}>Cancel</button>
</div>
);
}
export default App;

Properties

  1. When using the useInterval hook, you don’t need to memoize the callback with React.useCallback or similar. As the callback is not utilized as a dependency in the React.useEffect, you can pass your callback as is, and rest assured that it will be called correctly during the intervals.
./src/App.tsx
import React from 'react';
import { useInterval } from '@abhushanaj/react-hooks';
function App() {
// This is not required at all.
const callback = React.useCallback(() => {
console.log('Calling after interval');
}, []);
useInterval(callback, 1000);
return (
<div>
<p>I am now rendered!</p>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
callback()=>voidThe callback function to at specified intervals.N/A
durationnumber (optional)The duration of interval in ms.0
immediateboolean (optional)Whether or not to wait for the first interval.false

Return Value

The return value follows the signature [cancelInterval].

ParameterTypeDescriptionDefault
cancelInterval()=>voidA function to clear the interval and stop the execution.N/A