All hooks / Page, device, and user

useNetworkInformation

228 B minified and brotliedSourceMarkdown! Not available in Firefox, Safari, Safari iOS

The connection's data-saver setting and rough quality, from the Network Information API, updated when it changes.

Only Chromium browsers report it; elsewhere every field is unknown (saveData: false, effectiveType: 'unknown'), so treat unknown as a normal connection. Renders serverValue on the server and during hydration.

Import

import { useNetworkInformation } from '@vincent.ri/react-tils'
// or only this hook
import { useNetworkInformation } from '@vincent.ri/react-tils/useNetworkInformation'

Usage

const { saveData, effectiveType } = useNetworkInformation()
const lite = saveData || effectiveType === '2g' || effectiveType === 'slow-2g'
return lite ? <img src={poster} alt="" /> : <video src={clip} autoPlay muted loop />

Live demo

Chromium only; unknown elsewhere.

unknown · data saver off

When to use it

Adapting heavy content, e.g. don't autoplay video or prefetch when saveData is on or the connection is '2g'/'slow-2g'.

When not to

Choosing image sizes; <img srcset sizes> lets the browser decide. On the server, the Save-Data request header gives the same signal before any JS runs. Don't block features on it: the estimates are rough.

API

function useNetworkInformation(serverValue?: NetworkInfo): NetworkInfo
ParameterDescription
serverValueValue on the server and during hydration. Default: all unknown.

Types

export type NetworkInfo = {
  /** The user turned on a data saver. `false` where unknown. */
  saveData: boolean;
  /** Rough connection quality, or `'unknown'` where the browser doesn't say (Safari, Firefox). */
  effectiveType: "slow-2g" | "2g" | "3g" | "4g" | "unknown";
  /** Estimated bandwidth in Mbit/s, or `null` where unknown. */
  downlink: number | null;
  /** Estimated round-trip time in milliseconds, or `null` where unknown. */
  rtt: number | null;
};

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
Network Information APILimited availability61+79+✕✕38+✕
  • Where the API is missing, every field stays unknown: effectiveType: 'unknown', saveData: false, and null estimates.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).