useNetworkState
Browser & deviceTrack online/offline status and the Network Information API in one SSR-safe hook.
Install
$ npm install @usefy/use-network-stateQuick start
useNetworkState.tsx
import { useNetworkState } from "@usefy/use-network-state";
function ConnectivityBanner() {
const { online } = useNetworkState();
if (online) return null;
return <div role="alert">You are offline.</div>;
}API reference
useNetworkState(): NetworkState
Takes no arguments and returns the current network state. The object identity is stable between updates that don't change any observed value (safe as an effect dependency).
NetworkState
| Field | Type | Description |
|---|---|---|
online | boolean | From navigator.onLine. Defaults to true on the server / without a navigator. |
since | Date | undefined | Timestamp of the last online/offline transition. undefined until the first transition occurs. |
downlink | number | undefined | Estimated downlink speed in Mb/s. |
downlinkMax | number | undefined | Maximum downlink speed of the underlying technology, in Mb/s. |
effectiveType | "slow-2g" | "2g" | "3g" | "4g" | undefined | Effective connection type. |
rtt | number | undefined | Estimated effective round-trip time in ms. |
saveData | boolean | undefined | Whether the user has requested reduced data usage ("Data Saver"). |
type | ConnectionType | undefined | Physical connection type ("wifi", "cellular", "ethernet", …). |
All fields except online are undefined when the Network Information API is
unsupported.
Exported types & helpers
import {
useNetworkState,
getNetworkState, // read a one-off snapshot outside React
getConnection, // resolve navigator.connection (+ vendor prefixes)
isNavigatorAvailable, // SSR guard
isNetworkInformationSupported, // feature detection
areNetworkStatesEqual, // field-by-field comparison
SERVER_NETWORK_STATE, // the inert server snapshot ({ online: true })
type NetworkState,
type UseNetworkStateReturn,
type EffectiveConnectionType,
type ConnectionType,
type NetworkInformationLike,
} from "@usefy/use-network-state";
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.