Detecting Internet connectivity in react native using NetInfo

Ajmal Hasan - Dec 8 '23 - - Dev Community

Image description

The @react-native-community/netinfo package is a React Native community-maintained module that provides a simple API to get information about the network connectivity status on a device. It allows you to monitor changes in network connectivity, such as when the device goes online or offline.

Here are some key points about @react-native-community/netinfo:


1. Installation:

You can install the package using npm or yarn:

npm install @react-native-community/netinfo && cd ios && pod install
or
yarn add @react-native-community/netinfo && cd ios && pod install


Note:
Add these android permission to access network status:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission
        android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission
        android:name="android.permission.ACCESS_WIFI_STATE" />
Enter fullscreen mode Exit fullscreen mode

2. Usage:

Import the NetInfo module from @react-native-community/netinfo and use its methods to check the network status.
(REF->)
NetInfoComp.jsx

import React, { useCallback, useState } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import NetInfo from '@react-native-community/netinfo';
import { StyleSheet, Text, View } from 'react-native';
import { hasNotch } from 'react-native-device-info';
import Animated, { BounceIn } from 'react-native-reanimated';
import { strings } from '../i18n';
import { fontSize } from '../utils/fonts';
import { Colors } from '../utils/colors';

const NetInfoComp = () => {
  const [hasInternet, setHasInternet] = useState(true);
  useFocusEffect(
    useCallback(() => {
      const netInfoSubscription = NetInfo.addEventListener((state) => {
        setHasInternet(state.isConnected);
      });
      return () => {
        netInfoSubscription();
      };
    }, [])
  );
  return !hasInternet ? (
    <Animated.View entering={BounceIn.delay(400)} style={styles.container}>
      <Text style={styles.text1}>{strings('common.noInternet')}</Text>
      <Text numberOfLines={1} style={styles.text2}>
        {strings('common.plzCheckInternet')}
      </Text>
    </Animated.View>
  ) : null;
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    paddingVertical: 15,
    position: 'absolute',
    zIndex: 1,
    top: hasNotch() ? 60 : 20,
    marginHorizontal: 10,
    alignSelf: 'center',
    backgroundColor: 'white',
    borderRadius: 10,
    elevation: 5, // Android shadow
    shadowColor: '#000', // iOS shadow
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    borderStartWidth: 5,
    borderColor: Colors.commonDanger,
  },
  text1: { textAlign: 'left', fontSize: fontSize.large, fontWeight: 'bold', marginBottom: 5 },
  text2: { textAlign: 'left', fontWeight: '500' },
});

export default NetInfoComp;

Enter fullscreen mode Exit fullscreen mode

then add use this component inside your NavigationContainer of react navigation since we are also using useFocusEffect from react navigation

route.jsx (REF->)

      <NavigationContainer>
        <NetInfoComp /> // <--
          <RootStack.Screen name="HomeScreen" component={HomeScreen} />
        </RootStack.Navigator>
      </NavigationContainer>
Enter fullscreen mode Exit fullscreen mode

3. Response we will get from NetInfo state:

{"details": {"ipAddress": "1xx.1xx.x.1x", "isConnectionExpensive": false, "subnet": "xxx.xx5.2xx.x"}, "isConnected": true, "isInternetReachable": null, "type": "wifi"}
Enter fullscreen mode Exit fullscreen mode

Event Listeners:
The addEventListener method allows you to listen for changes in the network status. When the network status changes, the provided callback function is invoked with the updated network state.

Using this package can be beneficial when your React Native application needs to adapt its behavior based on network connectivity, such as fetching data from an API when the device is online and showing a message when offline.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .