Skip to main content

useNetworkEfficiency

Description and use case

useNetworkEfficiency reads Resource Timing entries and reports payload sizes for matching resources. It is useful for API-heavy screens where a response that feels acceptable on desktop broadband can become expensive on mobile networks.

The hook prefers transferSize, then falls back to encodedBodySize and decodedBodySize when the browser exposes those fields. Cross-origin resources may report 0 unless the response includes the appropriate Timing-Allow-Origin header.

When the Network Information API is available, the configured threshold is lowered for 3g, 2g, and slow-2g connections. Browsers without that API keep the configured threshold and continue to work.

API signature

function useNetworkEfficiency(options?: UseNetworkEfficiencyOptions): UseNetworkEfficiencyReturn;

Parameters

NameTypeRequiredDescription
options.resourceFilterstring | RegExp | (entry) => boolNoMatches resource URLs. Omit to inspect all resource entries.
options.maxSizeInBytesnumberNoBase payload threshold in bytes. Default 512000 (500KB).
options.onWarning(entry) => voidNoCalled when a matching payload exceeds the effective threshold.
options.enabledbooleanNoSet false to disable resource scanning and observation.

Return value

FieldTypeDescription
lastPayloadSizenumber | nullLatest matching payload size in bytes, or null before a match.
isInefficientbooleanWhether the latest matching payload exceeds the effective threshold.
latestNetworkEfficiencyEntry | nullLatest matching resource summary.
effectiveMaxSizeInBytesnumberThreshold after Network Information API adjustments.
effectiveTypestring | nullConnection type such as 3g, or null when unavailable.
isSupportedbooleanWhether this browser exposes Resource Timing entries.

Code example

import { useNetworkEfficiency } from 'react-perf-hooks';

export function HeavyDataProbe() {
const { lastPayloadSize, isInefficient, effectiveMaxSizeInBytes, effectiveType } =
useNetworkEfficiency({
resourceFilter: '/api/v1/heavy-data',
maxSizeInBytes: 1024 * 500,
onWarning: (entry) => {
navigator.sendBeacon('/analytics/network-payload', JSON.stringify(entry));
},
});

return (
<span>
{isInefficient
? `Payload ${formatBytes(lastPayloadSize)} exceeded ${formatBytes(effectiveMaxSizeInBytes)}${
effectiveType ? ` on ${effectiveType}` : ''
}`
: null}
</span>
);
}

function formatBytes(value: number | null) {
if (value === null) return 'n/a';

return `${(value / 1024).toFixed(0)} KB`;
}