Your app may need to detect the user's internet connectivity at times. If the user is offline or doesn't have access to a decent internet connection, you can operate on a different path. An illustration of this in practice would be if your program broadcasts remote videos and requires a strong internet connection. If the user doesn't have access to the internet or a reliable connection, you can concentrate on seamlessly informing them that the video can't be streamed. This is preferable to throwing an error and leaving the user perplexed.
The React Native Network Info API, which is available in the react-native community repo, gives us information about the network's connection type and quality.
Note: The NetInfo API that comes pre-installed with React Native is deprecated. The official React Native documentation suggests that we use the React Native Network Info API, which we'll cover in this blog article.
Let's get into the details.
Key Features
The React Native Network Info API can be used to know about the user's app's internet connectivity. The following are some of the API's key features:
-
Android, iOS, macOS, and Windows are all supported.
-
Obtain information about the current state of the network connection.
-
Find out what kind of network connection you have right now (wifi, cellular, Bluetooth, etc.)
-
Determine the current cellular connection generation (3g, 4g, etc.)
-
Ability to perform network reachability tests with a timeout.
Installation
It's simple to set up and use the library.
Add package to your project using yarn.
yarn add @react-native-community/netinfo
You don't need to bother about manually linking the libraries if you're using React Native >= 0.60.
If you're linking with CocoaPods on iOS, be sure to use the command below:
$ 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
Okay, now that you've installed the React Native Network Info package, you're ready to figure out the app's internet connection data. Let's take a look at how to use this library.
First and foremost, as demonstrated below, import the NetInfo API from the package:
import NetInfo from '@react-native-community/netinfo'
useNetInfo Hook
Using the useNetInfo hook within your functional component is the simplest approach to get net information without using event handlers. This is part of the network information library that we're working with.
The useNetInfo hook returns the NetInfoState type, which describes the current state of the network in the example below:
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 the current network state to us. Let's have a look at the properties that the NetInfoState API supports.
-
type — Returns the NetInfoStateType of the current connection (cellular, wifi, bluetooth, etc.)
-
isConnected — Boolean value that indicates whether there is an active network connection (cellular, wifi, Bluetooth, etc.)
-
isInternetReachable — A Boolean value that determines whether or not the internet can be accessed using the current connection.
-
isWifiEnabled (Android only) — A Boolean value indicating whether or not wifi is enabled.
-
details — Depending on the type of network connection, this can offer us with more information about the connection. The cost of a connection can be determined by a variety of factors. Here you can get more information about wifi and cellular.
Typically, we only need to know the type of internet connection, whether the user is connected, and if their internet is reachable when building mobile apps. In some cases, you might need further information about the user's connection, which you can get using this library. Let's build on our last example to get more information 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()
You'll need to add event listeners to subscribe for updates to the user's network connection if you're getting NetInfo from a class component. The useNetInfo hook can be used to get the current network connection within a functional component. The hook keeps an ear out for behind-the-scenes information.
Let's look at an example of how we can use event listeners in your component to get network connection information.
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()
}
We're subscribing to any changes in the componentDidMount() lifecycle method in the previous code snippet. After you subscribe, the listener will be contacted with the most up-to-date network information. When the connection state changes, the callback is called with a parameter of type NetInfoState.
fetch()
The fetch() method can be used to get network connection information once only, without having to subscribe to any updates within your component. It returns a promise with a NetInfoState type as the result.
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
configure()
You may also use the API to set up the library with a set of setup options. You can adjust the default values by providing the values you want to change. If you're going to use this function, make sure you call it as soon as your app starts.
An example of how to use the configure method is shown below:
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
That's all there is to it, guys. If you want to build offline apps or apps that rely on knowing network connection data, check out React Native Net Info.
If you're 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. And if you did, don't forget to share it with your network.