Comments

Network Connection In Your React Native App

There are times when your app may need to detect the user’s internet connectivity. You may work on an alternate path if the user is offline or has no access to good internet connection. A real world example to this could be one where, your app streams remote videos and needs good internet connection. In case the user doesn’t have internet or a reachable connection you can work on seamlessly letting the user know that the video is unable to stream. This is better than throwing an error, leaving the user confused.

The React Native Network Info API which is part of the react native community repo provides us details on both the connection type and quality of the network.

Note: The NetInfo API that comes with React Native out of the box is deprecated. The official React Native docs recommend that we use the React Native Network Info API that we are going to learn about in this blog post.

Let’s dive into the details.

Key Features

The React Native Network Info API can be used to understand the internet connectivity details of the user’s app. Here are the key features of this API:

  • Works for Android, iOS, macOS and Windows.
  • Obtain current state of network connection.
  • Obtain current type of network connection (wifi, cellular, bluetooth, etc.)
  • Determine current generation of cellular connection (3g, 4g, etc.)
  • Ability to perform network reachability tests with a timeout.

Installation

The library is quite easy to setup and get going.

Add package to your project using yarn.

yarn add @react-native-community/netinfo

If you are using React Native version >= 0.60, you don’t need to worry about manually linking the libraries.

Make sure you run the following command for iOS for linking using CocoaPods.

$ npx pod-install

On Android modify the android/build.gradle config.

buildscript {
  ext {
    buildToolsVersion = "28.0.3"
    minSdkVersion = 16
    compileSdkVersion = 28
    targetSdkVersion = 28
    # Only using Android Support libraries
    supportLibVersion = "28.0.0"
    # If using Android X
    # Remove 'supportLibVersion' property and add specific versions for AndroidX libraries as 
    shown below
    # androidXCore = "1.0.2" 
    // Add other AndroidX dependencies
  } 

For additional details on installation refer to the official documentation.

Usage

Alright, you have installed the React Native Network Info package and are now all set to identify the internet connection details of the app. Let’s walk through the steps to use this library.

First things first, import the NetInfo API from the package as shown below:

import NetInfo from '@react-native-community/netinfo'

useNetInfo Hook

The easiest way to obtain the net information without using event handlers would be using the useNetInfo hook within your functional component. This is available as a part of the network information library that we are using.

In the example below we are using the useNetInfo hook which returns the NetInfoState type that describes the current state of the network.

import {useNetInfo} from "@react-native-community/netinfo";

const MyComponent = () => {
  // returns a hook with the NetInfoState type.
  const netInfo = useNetInfo();
  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

NetInfoState API

The useNetInfo hook returns to us the current state of the network. Let’s look into the properties supported by the NetInfoState API.

  • type – Returns the NetInfoStateType of the current connection (cellular, wifi, bluetooth, etc..)
  • isConnected – Boolean value that tells if there is an active network connection.
  • isInternetReachable – Boolean value that determines if the internet is reachable with the current connection
  • isWifiEnabled (Android only) – Boolean value indicating if wifi is enabled or not.
  • details – This can provide us further details on the connection depending upon the type of network connection. All types of connections can determine if the connection is expensive. You can obtain details additional wifi/cellular details from here.

Typically, while designing mobile apps, we may just need to know the type of the internet connection, whether the user is connected, and if their internet is reachable. In certain situations you may need to know additional details about the user’s connection which can be obtained from this library. Let’s expand our previous example to obtain further details from the netinfo hook.

import {useNetInfo} from "@react-native-community/netinfo";

const MyComponent = () => {
  // returns a hook with the NetInfoState type.
  const netInfo = useNetInfo();
  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
      <Text>Is Connection Expensive ? 
      {netInfo.isConnectionExpensive.toString()}</Text>
      { netInfo.type == "wifi" && 
        <>
        <Text>SSID: {netInfo.details.ssid}</Text>
        <Text>BSSID: {netInfo.details.bssid}</Text>
        </>
      }
    </View>
  );
};

addEventListener()

If you are obtaining the NetInfo within a class component, you will need to add event listeners to subscribe for updates to the user’s network connection. Within a functional component, you could obtain the current network connection with the useNetInfo hook. The hook listens for updates behind the scenes.

Let’s look at an example of how we can obtain the network connection information using event listeners within your component.

let unsubscribe = null
componentDidMount() {
  // Subscribe
  unsubscribe = NetInfo.addEventListener(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
 });
}

componentWillUnmount() {
  // Unsubscribe
  if (unsubscribe != null) unsubscribe()
}

In the above code snippet, we are subscribing for any changes within the componentDidMount() lifecycle method. The listener will be called with the latest network information after you subscribe.  The callback is called with a parameter of type NetInfoState whenever the connection state changes.

fetch()

If you are looking to obtain the network connection information just once without subscribing to any updates within your component you can use the fetch() method. It returns a promise that resolves to a NetInfoState type.

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

configure()

The API also allows you to configure the library with a given set of configuration parameters. You can provide the values that you want to change from the initial default values. If you are using this method, make sure to call this when your app is started.

Here is an example of setting up the configure method.

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
});

Conclusion

Well that’s a wrap folks. Do checkout React Native Net Info, if you are looking to build offline ready apps or apps that rely on knowing the network connection details.

If you are looking for a course that gets you started with React Native and teaches the fundamentals, checkout Mosh’s course linked below.

Ultimate React Native Course – Code With Mosh

I hope you enjoyed this article. See you again with more articles. If you liked this post, don’t forget to share it with your network. You can follow me on twitter @AdhithiRavi for more updates or if you have any questions.

Adhithi Ravichandran is a Software Consultant based in Kansas City. She is currently working on building apps with React, React Native and GraphQL. She is a Conference Speaker, Pluralsight Author, Blogger and Software Consultant. She is passionate about teaching and thrives to contribute to the tech community with her courses, blog posts and speaking engagements.
Tags: , , , , ,

3 responses to “Network Connection In Your React Native App”

  1. Hi, how can you get the carrier that has the internet connection if you have two sims, and also how can you list all sims in the phone.
    Thanks

  2. There was a habit of overworking at school after a bad night, anyone can write my work, there is this site at https://www.edugeeksclub.com/research-proposal/, a specialist does any written work that I want and at the right time for a small price

  3. ivoryhoward says:

    I didn’t have any expectations concerning that title, but the more I was astonished. The author did a great job. I spent a few minutes reading and checking the facts. Everything is very clear and understandable. I like posts that fill in your knowledge gaps. This one is of the sort.

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts

    %d bloggers like this: