useNetworkState
React hook to monitor online/offline status and Network Information API metrics with event callbacks.
Demo
OfflineToggle network in DevTools to test callbacks
online—
effectiveType—
downlink—
rtt—
saveData—
Usage
Simple — single callback fires on every network change:
Object form — granular callbacks:
effectiveType,downlink,rttandsaveDatacome from the Network Information API and areundefinedin browsers that do not support it (Safari, Firefox).
Parameters
Simple form
| Parameter | Type | Description |
|---|---|---|
callback | (state: NetworkState) => void | Fires on every network change — online, offline, and connection quality changes. |
Object form
| Property | Type | Description |
|---|---|---|
onChange | (state: NetworkState) => void | Fires on every network change. |
onOnline | (state: NetworkState) => void | Fires when the browser goes online. |
onOffline | (state: NetworkState) => void | Fires when the browser goes offline. |
Return Values
Returns a NetworkState object:
| Property | Type | Description |
|---|---|---|
online | boolean | Whether the browser has network access. |
effectiveType | '4g' | '3g' | '2g' | 'slow-2g' | undefined | Estimated connection type. |
downlink | number | undefined | Estimated bandwidth in Mbps. |
rtt | number | undefined | Estimated round-trip time in ms. |
saveData | boolean | undefined | Whether the user has enabled data saver. |