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;
Properties
- When using the
useInterval
hook, you don’t need to memoize the callback withReact.useCallback
or similar. As the callback is not utilized as a dependency in theReact.useEffect
, you can pass your callback as is, and rest assured that it will be called correctly during the intervals.
API Reference
Parameters
Parameter | Type | Description | Default |
---|---|---|---|
callback | ()=>void | The callback function to at specified intervals. | N/A |
duration | number (optional) | The duration of interval in ms . | 0 |
immediate | boolean (optional) | Whether or not to wait for the first interval. | false |
Return Value
The return value follows the signature [cancelInterval]
.
Parameter | Type | Description | Default |
---|---|---|---|
cancelInterval | ()=>void | A function to clear the interval and stop the execution. | N/A |