Skip to content

此页面的翻译正在准备中,暂时显示英文原文。

useNetworkStatus

useNetworkStatus is a React hook that provides access to the Network Information API. It provides raw network connection data. Returns undefined for all properties if the API is not supported (e.g., Safari, Firefox). Browser Support: - Chrome/Edge (Android): Full support - Chrome/Edge (Desktop): Partial support (effectiveType, downlink, rtt, saveData) - Firefox: Not supported - Safari: Not supported

Interface

ts
function useNetworkStatus(): NetworkStatus;

Parameters

Return Value

  • NetworkStatus

    status information

    • effectiveType

      Connection quality
      : 'slow-2g' | '2g' | '3g' | '4g' - type - Physical connection
      : 'wifi' | 'cellular' | 'ethernet' | etc. - downlink - Downlink speed in Mbps - rtt - Round-trip time in milliseconds - saveData - User's data saver preference.

Example

tsx
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" />
  );
}

基于 MIT 许可证发布。