@resilient

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-hooks

Usage

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> | void

The function to call on each poll interval.

options?PollingOptions

Configuration options for the polling behavior.

Options

baseInterval?number

Base polling interval in ms (used on 4G/WiFi). Default: 5000.

maxInterval?number

Maximum interval cap in ms. Default: 60000.

jitter?boolean

Add random jitter to prevent thundering herd. Default: true.

pauseWhenOffline?boolean

Automatically pause polling when offline. Default: true.

enabled?boolean

Start polling immediately. Default: true.

Returns

statePollingState

Current polling state (isPolling, isPaused, currentInterval, errorCount, lastError).

pause() => void

Pause polling manually.

resume() => void

Resume 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.