All hooks / Page, device, and user
useNetworkInformation
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.
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| Parameter | Description |
|---|---|
serverValue | Value 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
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| Network Information APILimited availability | 61+ | 79+ | ✕ | ✕ | 38+ | ✕ |
- Where the API is missing, every field stays unknown:
effectiveType: 'unknown',saveData: false, andnullestimates.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).