useAdaptivePolling
Smart polling that adapts its frequency based on network conditions with pause/resume controls.
Live Demo
Status
Stopped
Interval
5s (4G)
Fetches
0
Errors
0
Current Random Number
—
How it works
The polling interval automatically adjusts based on your network speed. 4G = 5s, 3G = 10s, 2G = 15s. Use the controls to pause, resume, or trigger immediately.
Installation
npm install react-resilient-hooksUsage
import { useAdaptivePolling } from 'react-resilient-hooks';
function MyComponent() {
const fetchData = async () => {
const response = await fetch('/api/data');
return response.json();
};
const { state, pause, resume, triggerNow } = useAdaptivePolling(
fetchData,
{
baseInterval: 5000,
maxInterval: 30000,
pauseWhenOffline: true,
}
);
return (
<div>
<p>Status: {state.isPolling ? 'Polling' : 'Paused'}</p>
<p>Errors: {state.errorCount}</p>
<button onClick={pause}>Pause</button>
<button onClick={resume}>Resume</button>
<button onClick={triggerNow}>Fetch Now</button>
</div>
);
}API
Parameters
callback() => Promise<void> | voidThe function to call on each poll interval.
options?PollingOptionsConfiguration options for the polling behavior.
Options
baseInterval?numberBase polling interval in ms (used on 4G/WiFi). Default: 5000.
maxInterval?numberMaximum interval cap in ms. Default: 60000.
jitter?booleanAdd random jitter to prevent thundering herd. Default: true.
pauseWhenOffline?booleanAutomatically pause polling when offline. Default: true.
enabled?booleanStart polling immediately. Default: true.
Returns
statePollingStateCurrent polling state (isPolling, isPaused, currentInterval, errorCount, lastError).
pause() => voidPause polling manually.
resume() => voidResume polling manually.
triggerNow() => Promise<void>Immediately trigger the callback without waiting for next interval.
How It Works
The hook dynamically adjusts polling intervals based on network conditions:
- 4G / WiFi: Uses the base interval (e.g., 5s)
- 3G: Doubles the interval (e.g., 10s)
- 2G: Triples the interval (e.g., 15s)
- Offline: Pauses polling entirely
When jitter is enabled, a random delay of 0-10% is added to prevent multiple clients from polling at the exact same time.