Skip to content
usefy

useNetworkState

Browser & device

Track online/offline status and the Network Information API in one SSR-safe hook.

Install

$ npm install @usefy/use-network-state

Quick 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

FieldTypeDescription
onlinebooleanFrom navigator.onLine. Defaults to true on the server / without a navigator.
sinceDate | undefinedTimestamp of the last online/offline transition. undefined until the first transition occurs.
downlinknumber | undefinedEstimated downlink speed in Mb/s.
downlinkMaxnumber | undefinedMaximum downlink speed of the underlying technology, in Mb/s.
effectiveType"slow-2g" | "2g" | "3g" | "4g" | undefinedEffective connection type.
rttnumber | undefinedEstimated effective round-trip time in ms.
saveDataboolean | undefinedWhether the user has requested reduced data usage ("Data Saver").
typeConnectionType | undefinedPhysical 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.

More in browser & device