@react-native-community/netinfo

repository·master·Indexed 24 days ago

https://github.com/react-native-netinfo/react-native-netinfo

React Native Network Info API for iOS, Android, macOS, Windows, and Web. This library provides tools to monitor network connection type and quality, featuring a global singleton instance and isolated instances via the useNetInfoInstance hook. It includes utilities for subscribing to network changes, fetching current state, and forcing state refreshes.

Tokens
6.7K
Snippets
22
Records
35
Agent score
79%

What's inside @react-native-community/netinfo

  1. How Global vs Isolated instances work

    master

    The library uses an internal network state manager class. You can interact with it in two ways:

    1. Global Instance: Uses a singleton instance. This is the easiest way to access network state across your entire app using global functions or the useNetInfo hook.
    2. Isolated Instance: Allows you to create separate, independently configured instances of the network manager. This is useful if you need different configurations for different parts of your application.
  2. Understand the NetInfoState object

    master

    The NetInfoState object describes the current state of the network. It contains the connection type, connectivity status, and internet reachability. The details property provides additional metadata that varies based on the connection type.

    Core Properties

    • type: The connection type (NetInfoStateType).
    • isConnected: boolean or null. Indicates if there is an active connection. Defaults to null for unknown networks on most platforms.
    • isInternetReachable: boolean or null. Indicates if the internet is reachable via the current connection.
    • isWifiEnabled: boolean (Android only). Indicates if WiFi is ON or OFF.
    • details: An object containing type-specific metadata.
  3. Mock NetInfo for Jest tests

    master

    To run Jest tests without errors related to the native module, you must mock @react-native-community/netinfo.

    1. Add a setup file to your Jest configuration (e.g., in package.json or jest.config.js):
    setupFiles: ['<rootDir>/jest.setup.js']
    1. In your jest.setup.js file, import the provided mock and apply it to the module:
    import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js';
    
    jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
  4. Handle network state sync on iOS background/foreground transitions

    master

    Due to limitations in the iOS SCNetworkReachability API, network change events (like switching Wi-Fi networks) may not be received while the app is in the background. This can cause your app's network state to be out of sync when the app returns to the foreground.

    To ensure the network state is accurate, you should manually re-fetch the current state whenever the app transitions to the active state using AppState.

      useEffect(() => {
        const subAppState = AppState.addEventListener("change", async (nextAppState) => {
          if (IS_IOS_DEVICE && nextAppState=='active') {
            let newNetInfo = await NativeModules.RNCNetInfo.getCurrentState('wifi');
            //your code here 
          }
        });
        const unsubNetState = NetInfo.addEventListener(state => {
            //your code here
        });
        return () => {
            if (subAppState) {
                subAppState.remove();
            }
            unsubNetState();
        };
      },[]);
  5. Configure platform-specific setup

    master

    Depending on your platform, follow these steps after installation:

    • iOS: Run $ npx pod-install to install CocoaPods.
    • Android (with AndroidX): Ensure your android/build.gradle is configured with appropriate buildToolsVersion, minSdkVersion, compileSdkVersion, and targetSdkVersion.
    • macOS: Autolinking is not available. You must manually link RNCNetInfo.xcodeproj (found in node_modules/@react-native-community/react-native-netinfo/macos) to your project's Libraries folder and add libRNCNetInfo-macOS.a to your Build Phases -> Link Binary with Libraries.
    • Windows: Autolinking works automatically on react-native-windows >= 0.63. Requires MSVC build tools v142 or newer. Supports x86, x64, or arm64 (32-bit arm is not supported).
  6. Understand Global vs Isolated NetInfo instances

    master

    NetInfo provides two distinct ways to consume network information:

    1. Global Singleton: Accessed via NetInfo.fetch(), NetInfo.addEventListener(), NetInfo.refresh(), and the useNetInfo() hook. Changes to the global configuration via NetInfo.configure() affect all these calls. This is the standard way to monitor network state across an entire application.

    2. Isolated Instances: Accessed via the useNetInfoInstance() hook. This creates a completely separate State manager. Calling NetInfo.configure() or using other global methods will have no effect on an isolated instance. This is ideal for components that require specific network monitoring logic that should not interfere with the app's primary network state tracking.

  7. Troubleshoot iOS Simulator network notifications

    master
    There is a known issue with the iOS Simulator where it may fail to receive network change notifications correctly when the host machine disconnects and reconnects to Wi-Fi. If you encounter issues with network event detection on iOS, test on a physical device before reporting a bug.
  8. Manage an isolated instance with useNetInfoInstance()

    master

    The useNetInfoInstance() hook creates and manages an isolated network manager instance. Unlike useNetInfo(), which uses the global instance, this hook provides its own local state and configuration.

    • Returns: An object containing { netInfo, refresh }.
    • isPaused: You can pass a boolean as the first argument to pause the hook's internal network checks.
    • configuration: You can pass a configuration object as the second argument. This configuration is local to this specific instance and does not affect the global NetInfo instance.
    import { useNetInfoInstance } from "@react-native-community/netinfo";
    
    const YourComponent = () => {
      const isPaused = false;
      const config = {
        reachabilityUrl: 'https://clients3.google.com/generate_204',
        reachabilityTest: async (response) => response.status === 204,
        reachabilityLongTimeout: 60 * 1000,
        reachabilityShortTimeout: 5 * 1000,
        reachabilityRequestTimeout: 15 * 1000,
        reachabilityShouldRun: () => true,
        shouldFetchWiFiSSID: true,
        useNativeReachability: false
      };
      
      const { netInfo, refresh } = useNetInfoInstance(isPaused, config);
      //...
    };
  9. Fetch the current network state with fetch()

    master

    Use NetInfo.fetch() to get a one-time snapshot of the current network state. It returns a Promise resolving to a NetInfoState object. You can optionally pass an interface string (e.g., 'wifi') to ensure the returned state matches that type.

    NetInfo.fetch().then(state => {
      console.log("Connection type", state.type);
      console.log("Is connected?", state.isConnected);
    });
  10. Configure the global NetInfo instance

    master

    Use NetInfo.configure() to set global settings for the library, such as reachability URLs and timeouts. This is best called at application startup. Note that calling configure() will stop all previously added listeners.

    Important for iOS: To retrieve WiFi SSID/BSSID, you must set shouldFetchWiFiSSID: true and meet Apple's specific requirements. Setting this to true without meeting requirements may leak memory.

    NetInfo.configure({
      reachabilityUrl: 'https://clients3.google.com/generate_204',
      reachabilityTest: async (response) => response.status === 204,
      reachabilityLongTimeout: 60 * 1000, // 60s
      reachabilityShortTimeout: 5 * 1000, // 5s
      reachabilityRequestTimeout: 15 * 1000, // 15s
      reachabilityShouldRun: () => true,
      shouldFetchWiFiSSID: true, // met iOS requirements to get SSID. Will leak memory if set to true without meeting requirements.
      useNativeReachability: false
    });