What is @react-native-community/netinfo?
@react-native-community/netinfo is a React Native library that provides information about the device's network connection state. It allows developers to detect the type of network connection (WiFi, cellular, etc.), whether the device is connected to the internet, and other related details.
What are @react-native-community/netinfo's main functionalities?
Check current network state
This feature allows you to fetch the current network state, including the connection type (e.g., WiFi, cellular) and whether the device is connected to the internet.
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then(state => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
});
Subscribe to network state changes
This feature allows you to subscribe to network state changes, so you can react to changes in the network connection in real-time.
import NetInfo from '@react-native-community/netinfo';
const unsubscribe = NetInfo.addEventListener(state => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
});
// Later, you can unsubscribe to stop listening for updates
unsubscribe();
Check if the device is connected to the internet
This feature allows you to check if the device is currently connected to the internet.
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then(state => {
console.log('Is connected?', state.isConnected);
});
Get detailed network information
This feature provides detailed information about the network connection, including whether the internet is reachable and additional details specific to the connection type.
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then(state => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
console.log('Is internet reachable?', state.isInternetReachable);
console.log('Details:', state.details);
});
Other packages similar to @react-native-community/netinfo
react-native-network-info
react-native-network-info is another React Native library that provides information about the device's network state. It offers functionalities such as getting the SSID of the connected WiFi network and the IP address of the device. However, it does not provide as comprehensive a set of features for monitoring network state changes as @react-native-community/netinfo.
react-native-connection-info
react-native-connection-info is a library that provides basic information about the network connection, such as the connection type and whether the device is connected to the internet. It is simpler and less feature-rich compared to @react-native-community/netinfo, making it suitable for applications that need only basic network information.
React Native Network Info API for Android, iOS & Windows. It allows you to get information on:
- Connection type
- Connection quality
Getting started
Install the library using either Yarn:
yarn add @react-native-community/netinfo
or npm:
npm install --save @react-native-community/netinfo
You then need to link the native parts of the library for the platforms you are using. The easiest way to link the library is using the CLI tool by running this command from the root of your project:
react-native link @react-native-community/netinfo
If you can't or don't want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):
Manually link the library on iOS
Either follow the instructions in the React Native documentation to manually link the framework or link using Cocoapods by adding this to your Podfile
:
pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'
Manually link the library on Android
Make the following changes:
android/settings.gradle
include ':react-native-community-netinfo'
project(':react-native-community-netinfo').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/netinfo/android')
android/app/build.gradle
dependencies {
...
implementation project(':react-native-community-netinfo')
}
android/app/src/main/.../MainApplication.java
On top, where imports are:
import com.reactnativecommunity.netinfo.NetInfoPackage;
Add the NetInfoPackage
class to your list of exported packages.
@Override
protected List<ReactPackage> getPackages() {
return Arrays.asList(
new MainReactPackage(),
new NetInfoPackage()
);
}
Manually link the library on Windows
- Open the solution in Visual Studio for your Windows apps
- Right click in the Explorer and click Add > Existing Project...
- Navigate to
./<app-name>/node_modules/@react-native-community/netinfo/windows/RNCNetInfo/
and add RNCNetInfo.csproj
- This time right click on your React Native Windows app under your solutions directory and click Add > Reference...
- Check the
RNCNetInfo
you just added and press ok - Open up
MainReactNativeHost.cs
for your app and edit the file like so:
+ using ReactNativeCommunity.NetInfo;
......
protected override List<IReactPackage> Packages => new List<IReactPackage>
{
new MainReactPackage(),
+ new RNCNetInfoPackage(),
};
React Native Compatibility
To use this library you need to ensure you are using the correct version of React Native. If you are using a version of React Native that is lower than 0.57
you will need to upgrade that before attempting to use this library.
@react-native-community/netinfo version | Required React Native Version |
---|
4.x.x | >= 0.60 or >= 0.59 if using Jetifier |
3.x.x | >= 0.59 |
2.x.x | >= 0.57 |
1.x.x | >= 0.57 |
Migrating from the core react-native
module
This module was created when the NetInfo was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from:
import { NetInfo } from "react-native";
to:
import NetInfo from "@react-native-community/netinfo";
Note that the API was updated after it was extracted from NetInfo to support some new features, however, the previous API is still available and works with no updates to your code.
Usage
Import the library:
import NetInfo from "@react-native-community/netinfo";
Get the network state once:
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
Subscribe to network state updates:
const unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
unsubscribe();
API
Types
NetInfoState
Describes the current state of the network. It is an object with these properties:
Property | Type | Description |
---|
type | NetInfoStateType | The type of the current connection. |
isConnected | boolean | If there is an active network connection. Note that this DOES NOT mean that internet is reachable. |
details | | The value depends on the type value. See below. |
The details
value depends on the type
value.
type
is none
or unknown
details
is null
.
type
is wifi
, bluetooth
, ethernet
, wimax
, vpn
, or other
details
has these properties:
Property | Type | Description |
---|
isConnectionExpensive | boolean | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
type
is cellular
details
has these properties:
Property | Type | Description |
---|
isConnectionExpensive | boolean | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
cellularGeneration | NetInfoCellularGeneration | The generation of the cell network the user is connected to. This can give an indication of speed, but no guarantees. |
NetInfoStateType
Describes the current type of network connection. It is an enum with these possible values:
Value | Platform | Description |
---|
none | Android, iOS, Windows | No network connection is active |
unknown | Android, iOS, Windows | The network state could not or has yet to be be determined |
cellular | Android, iOS, Windows | Active network over cellular |
wifi | Android, iOS, Windows | Active network over Wifi |
bluetooth | Android | Active network over Bluetooth |
ethernet | Android, Windows | Active network over wired ethernet |
wimax | Android | Active network over WiMax |
vpn | Android | Active network over VPN |
other | Android, iOS, Windows | Active network over another type of network |
NetInfoCellularGeneration
Describes the current generation of the cellular
connection. It is an enum with these possible values:
Value | Description |
---|
null | Either we are not currently connected to a cellular network or type could not be determined |
2g | Currently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections |
3g | Currently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, and UTMS type connections |
4g | Currently connected to a 4G cellular network. Includes HSPAP and LTE type connections |
Methods
fetch()
Returns a Promise
that resolves to a NetInfoState
object.
Example:
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
addEventListener()
Subscribe to connection information. The callback is called with a parameter of type NetInfoState
whenever the connection state changes. Your listener will be called with the latest information soon after you subscribe and then with any subsequent changes afterwards. You should not assume that the listener is called in the same way across devices or platforms.
Parameter | Type | Description |
---|
listener | (state: NetInfoState ) => void | The listener which will be called whenever the connection state changes |
Example:
const unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
unsubscribe();
useNetInfo()
A React Hook which can be used to get access to the latest state. It returns a hook with the NetInfoState
type.
Example:
import {useNetInfo} from "@react-native-community/netinfo";
const YourComplement = () => {
const netInfo = useNetInfo();
return (
<View>
<Text>Type: {netInfo.type}</Text>
<Text>Is Connected? {netInfo.isConnected}</Text>
</View>
);
};
Troubleshooting
Errors when building on Android
This library was migrated from using the support library to AndroidX in version 4.0.0
. All of your depenencies must be using either the support library or AndroidX. Using a mixture of the two is not possible.
From React Native 0.60 AndroidX is used by default.
If you need to either convert this library back to the support library (to use an older React Native version) or convert other libraries forward to use AndroidX (if they have not been updated yet), you can use the Jetifier tool.
Errors while running Jest tests
If you do not have a Jest Setup file configured, you should add the following to your Jest settings and create the jest.setup.js
file in project root:
setupFiles: ['<rootDir>/jest.setup.js']
You should then add the following to your Jest setup file to mock the NetInfo Native Module:
import { NativeModules } from 'react-native';
NativeModules.RNCNetInfo = {
getCurrentState: jest.fn(),
addListener: jest.fn(),
removeListeners: jest.fn()
};
Issues with the iOS simulator
There is a known issue with the iOS Simulator which causes it to not receive network change notifications correctly when the host machine disconnects and then connects to Wifi. If you are having issues with iOS then please test on an actual device before reporting any bugs.
Maintainers
Contributing
Please see the contributing guide.
License
The library is released under the MIT license. For more information see LICENSE
.