Skip to content

useNetworkAwarePolling – Network-Aware Smart Polling for React

Overview

Extends useSmartPolling with network awareness. Pauses when offline, and automatically increases the polling interval on slow connections (2g / slow-2g).

Usage

import { useNetworkAwarePolling } from "react-visibility-hooks";
function LiveFeed() {
const { data, isOnline, effectiveInterval } = useNetworkAwarePolling(
() => fetch("/api/feed").then((r) => r.json()),
{ interval: 5000, slowMultiplier: 3 },
);
return (
<div>
<p>Status: {isOnline ? "🟢 Online" : "🔴 Offline"}</p>
<p>Polling every {effectiveInterval / 1000}s</p>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}

API

Parameters

ParameterTypeDescription
fetchFn() => Promise<T>Async function returning data
optionsNetworkAwarePollingOptions?Optional configuration

Options (NetworkAwarePollingOptions)

Extends SmartPollingOptions:

OptionTypeDefaultDescription
intervalnumber5000Base polling interval in ms
enabledbooleantrueEnable / disable polling
slowMultipliernumber3Multiplier applied on 2g/slow-2g connections
pauseOfflinebooleantruePause polling when the browser is offline

Returns (NetworkAwarePollingResult<T>)

Inherits all properties from SmartPollingResult<T> plus:

PropertyTypeDescription
dataT | undefinedThe latest fetched data
isLoadingbooleantrue until the first fetch completes
isErrorbooleantrue if the last fetch threw
errorError | undefinedThe error object, if any
refetch() => Promise<void>Manually trigger a fetch
isOnlinebooleantrue when the browser reports being online
effectiveIntervalnumberActual polling interval after network adjustment