useIntervalWhen
Manage intervals against a flag conveniently using the useIntervalWhen hook.
The useIntervalWhen
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. The useIntervalWhen hook can stop and restart the action based on the when
flag.
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.
useIntervalWhen
Current duration is: 1000 ms
When: 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
useIntervalWhen
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.
-
When the
cancelInterval
is invoked then the interval cannot be triggered again.Use
when
flag to start/stop/resume the intervals and usecancelInterval
when you want to permanently stop the interval.
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 |
when | boolean (optional) | Whether or not to trigger the interval. | true |
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 |