useNetworkStatus
useNetworkStatus is a React hook that provides access to the Network Information API. It provides raw network connection data such as the connection type, quality, speed and the user's data saver preference. Every property is undefined if the API is not supported (e.g., Safari, Firefox).
Interface
function useNetworkStatus(): NetworkStatus;Parameters
This function does not accept any parameters.
Return Value
- NetworkStatus
Network status information
- effectiveType'slow-2g' | '2g' | '3g' | '4g' | undefined
Connection quality, or
undefinedif the API is not supported. - type'bluetooth' | 'cellular' | 'ethernet' | 'mixed' | 'none' | 'other' | 'unknown' | 'wifi' | 'wimax' | undefined
Physical connection type, or
undefinedif the API is not supported. - downlinknumber | undefined
Downlink speed in Mbps, or
undefinedif the API is not supported. - rttnumber | undefined
Round-trip time in milliseconds, or
undefinedif the API is not supported. - saveDataboolean | undefined
User's data saver preference, or
undefinedif the API is not supported.
- effectiveType'slow-2g' | '2g' | '3g' | '4g' | undefined
Example
Adaptive image quality
function AdaptiveImage() {
const { effectiveType, saveData } = useNetworkStatus();
// Determine quality based on your app's needs
const useHighQuality = effectiveType === '4g' && !saveData;
return (
<img src={useHighQuality ? 'high-res.jpg' : 'low-res.jpg'} alt="Content" />
);
}Conditional video autoplay
function VideoPlayer() {
const { type, downlink } = useNetworkStatus();
// Custom logic: only autoplay on wifi with good bandwidth
const shouldAutoplay = type === 'wifi' && (downlink ?? 0) > 5;
return <video src="video.mp4" autoPlay={shouldAutoplay} />;
}Notes
Browser support
- Chrome/Edge (Android): every property is supported
- Chrome/Edge (Desktop): partial support (
effectiveType,downlink,rttandsaveDataare available;typemay beundefined) - Firefox: not supported (every property is
undefined) - Safari: not supported (every property is
undefined)
SSR safety
The hook is safe during server-side rendering. On the server it returns an empty object {} and it subscribes to network changes only in the browser.
Recommendations
- Always check for
undefinedbefore using a value, since the API is not available in every browser - Provide a fallback for browsers without the Network Information API
- Use the hook to enhance the experience rather than for essential features
- Consider
effectiveTypetogether withsaveDatawhen deciding what to deliver