useNetworkState

React hook to monitor online/offline status and Network Information API metrics with event callbacks.

pnpm add react-callback-hooks

Demo

OfflineToggle network in DevTools to test callbacks
online
effectiveType
downlink
rtt
saveData

Usage

Simple — single callback fires on every network change:

import { useNetworkState } from 'react-callback-hooks'

const state = useNetworkState((state) => {
  console.log('network changed', state.online)
})

Object form — granular callbacks:

const state = useNetworkState({
  onChange: (state) => console.log('changed', state),
  onOnline: (state) => console.log('back online'),
  onOffline: (state) => console.log('went offline')
})

state.online // boolean
state.effectiveType // '4g' | '3g' | '2g' | 'slow-2g' | undefined
state.downlink // number (Mbps) | undefined
state.rtt // number (ms)   | undefined
state.saveData // boolean | undefined

effectiveType, downlink, rtt and saveData come from the Network Information API and are undefined in browsers that do not support it (Safari, Firefox).

Parameters

Simple form

ParameterTypeDescription
callback(state: NetworkState) => voidFires on every network change — online, offline, and connection quality changes.

Object form

PropertyTypeDescription
onChange(state: NetworkState) => voidFires on every network change.
onOnline(state: NetworkState) => voidFires when the browser goes online.
onOffline(state: NetworkState) => voidFires when the browser goes offline.

Return Values

Returns a NetworkState object:

PropertyTypeDescription
onlinebooleanWhether the browser has network access.
effectiveType'4g' | '3g' | '2g' | 'slow-2g' | undefinedEstimated connection type.
downlinknumber | undefinedEstimated bandwidth in Mbps.
rttnumber | undefinedEstimated round-trip time in ms.
saveDataboolean | undefinedWhether the user has enabled data saver.