Gathering detailed insights and metrics for @react-native-community/netinfo
Gathering detailed insights and metrics for @react-native-community/netinfo
Gathering detailed insights and metrics for @react-native-community/netinfo
Gathering detailed insights and metrics for @react-native-community/netinfo
React Native Network Info API for Android & iOS
npm install @react-native-community/netinfo
59.3
Supply Chain
63.7
Quality
75.5
Maintenance
50
Vulnerability
95.3
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,997 Stars
478 Commits
392 Forks
19 Watching
1 Branches
161 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (43.92%)
Java (25.69%)
Objective-C (13.22%)
C++ (9.73%)
JavaScript (5.13%)
Ruby (1.05%)
Shell (0.88%)
C (0.22%)
HTML (0.15%)
Cumulative downloads
Total Downloads
Last day
-5.3%
143,996
Compared to previous day
Last week
5.7%
737,770
Compared to previous week
Last month
9%
3,018,925
Compared to previous month
Last year
34.4%
30,203,279
Compared to previous year
1
44
@react-native-community/netinfo
React Native Network Info API for Android, iOS, macOS, Windows & Web. It allows you to get information on:
Install the library using either Yarn:
yarn add @react-native-community/netinfo
or npm:
npm install --save @react-native-community/netinfo
Linking the package manually is not required anymore with Autolinking.
iOS Platform:
$ npx pod-install
# CocoaPods on iOS needs this extra step
Android Platform with AndroidX:
Modify your android/build.gradle configuration:
buildscript {
ext {
buildToolsVersion = "xx.yy.zz"
minSdkVersion = xyz
compileSdkVersion = xyz
targetSdkVersion = xyz
}
macOS Platform:
Autolinking is not yet available on macOS. See the Manual linking steps for macOS below.
Open your project .xcodeproj
on xcode.
Right click on the Libraries folder and select Add files to "yourProjectName"
.
Add RNCNetInfo.xcodeproj
(located at node_modules/@react-native-community/react-native-netinfo/macos
) to your project Libraries.
Go to Build Phases -> Link Binary with Libraries
and add: libRNCNetInfo-macOS.a
.
Windows Platform:
Autolinking automatically works on RNW >= 0.63.
To use this library you need to ensure you are using the correct version of React Native. We support react-native 0.60+ with auto-linking.
If you are using a version of React Native that is lower than 0.60 check older versions of this README for details, but no support will be provided.
The web implementation heavily depends on the Network Information API which is still an is an experimental technology and thus it's not supported in every browser. If this API is not available the library will safely fallback to the old onLine property and return basic connection information.
AbortController is used to cancel network requests, and may not be available on Internet Explorer, though it is available on Edge https://caniuse.com/abortcontroller
Node v16 is the minimum required node version - AbortController
is only present in stable versions of node from v16 on
react-native
moduleThis 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 your imports from:
1import { NetInfo } from "react-native";
to:
1import 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.
Internally this library has a network state manager class to handle all the functionality and state. This library provides two options for instantiating the class:
Subscribe to network state updates:
1import { addEventListener } from "@react-native-community/netinfo"; 2 3// Subscribe 4const unsubscribe = addEventListener(state => { 5 console.log("Connection type", state.type); 6 console.log("Is connected?", state.isConnected); 7}); 8 9// Unsubscribe 10unsubscribe();
Get the network state once:
1import { fetch } from "@react-native-community/netinfo"; 2 3fetch().then(state => { 4 console.log("Connection type", state.type); 5 console.log("Is connected?", state.isConnected); 6});
Get network state updates from the global instance via a react hook:
1import { useNetInfo } from "@react-native-community/netinfo"; 2 3const { type, isConnected } = useNetInfo();
Use an isolated instance of the network manager:
1import { useNetInfoInstance } from "@react-native-community/netinfo"; 2 3const { netInfo: { type, isConnected }, refresh } = useNetInfoInstance();
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 , null | If there is an active network connection. Defaults to null on most platforms for unknown networks. Note: Web browsers report network type unknown for many otherwise valid networks (https://caniuse.com/netinfo), so isConnected may be true or false and represent a real connection status even for unknown network types in certain cases. |
isInternetReachable | boolean , null | If the internet is reachable with the currently active network connection. If unknown defaults to null |
isWifiEnabled | boolean | (Android only) Whether the device's WiFi is ON or OFF. |
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
details
has these properties:
Property | Platform | Type | Description |
---|---|---|---|
isConnectionExpensive | Android, iOS, macOS, Windows, Web | boolean | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
ssid | Android, iOS (not tvOS), Windows | string | The SSID of the network. May not be present, null , or an empty string if it cannot be determined. On iOS, your app must meet at least one of the following requirements and you must set the shouldFetchWiFiSSID configuration option or no attempt will be made to fetch the SSID. On Android, you need to have the ACCESS_FINE_LOCATION permission in your AndroidManifest.xml and accepted by the user. |
bssid | Android, iOS (not tvOS), Windows* | string | The BSSID of the network. May not be present, null , or an empty string if it cannot be determined. On iOS, make sure your app meets at least one of the following requirements. On Android, you need to have the ACCESS_FINE_LOCATION permission in your AndroidManifest.xml and accepted by the user. |
strength | Android, Windows | number | An integer number from 0 to 100 for the signal strength. May not be present if the signal strength cannot be determined. |
ipAddress | Android, iOS, macOS, Windows | string | The external IP address. Can be in IPv4 or IPv6 format. May not be present if it cannot be determined. |
subnet | Android, iOS, macOS | string | The subnet mask in IPv4 format. May not be present if it cannot be determined. |
frequency | Android, Windows* | number | Network frequency. Example: For 2.4 GHz networks, the method will return 2457. May not be present if it cannot be determined. |
linkSpeed | Android | number | The link speed in Mbps. |
rxLinkSpeed | Android | number | The current receive link speed in Mbps. (Android Q / API level 29 and above) |
txLinkSpeed | Android | number | The current transmit link speed in Mbps. (Android Q / API level 29 and above) |
*
Requires wiFiControl
capability in appxmanifest. Without it, these values will be null.
type
is cellular
details
has these properties:
Property | Platform | Type | Description |
---|---|---|---|
isConnectionExpensive | Android, iOS, macOS, Windows, Web | boolean | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
cellularGeneration | Android, iOS, Windows | NetInfoCellularGeneration | The generation of the cell network the user is connected to. This can give an indication of speed, but no guarantees. |
carrier | Android, iOS | string | The network carrier name. May not be present or may be empty if none can be determined. |
type
is 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. |
NetInfoStateType
Describes the current type of network connection. It is an enum with these possible values:
Value | Platform | Description |
---|---|---|
none | Android, iOS, macOS, Windows, Web | No network connection is active |
unknown | Android, iOS, macOS, Windows, Web | The network state could not or has yet to be be determined |
cellular | Android, iOS, Windows, Web | Active network over cellular |
wifi | Android, iOS, macOS, Windows, Web | Active network over Wifi |
bluetooth | Android, Web | Active network over Bluetooth |
ethernet | Android, macOS, Windows, Web | Active network over wired ethernet |
wimax | Android, Web | Active network over WiMax |
vpn | Android | Active network over VPN |
other | Android, iOS, macOS, Windows, Web | 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 |
5g | Currently connected to a 5G cellular network. Includes NRNSA (iOS only) and NR type connections |
NetInfoConfiguration
The configuration options for the library.
Property | Type | Default | Description |
---|---|---|---|
reachabilityUrl | string | https://clients3.google.com/generate_204 | The URL to call to test if the internet is reachable. Only used on platforms which do not supply internet reachability natively or if useNativeReachability is false . |
reachabilityHeaders | object | {} | A HTTP headers object, an object literal, or an array of two-item arrays to set request's headers, to use during the reachabilityUrl URL call to test if the internet is reachable. Defaults to {} . |
reachabilityMethod | NetInfoMethodType | HEAD | The HTTP request method to use to call reachabilityUrl URL to call to test if the internet is reachable. Defaults to HEAD . GET is also available |
reachabilityTest | (response: Response) => boolean | Promise.resolve(response.status === 204) | A function which is passed the Response from calling the reachability URL. It should return true if the response indicates that the internet is reachable. Only used on platforms which do not supply internet reachability natively or if useNativeReachability is false . |
reachabilityShortTimeout | number | 5 seconds | The number of milliseconds between internet reachability checks when the internet was not previously detected. Only used on platforms which do not supply internet reachability natively or if useNativeReachability is false . |
reachabilityLongTimeout | number | 60 seconds | The number of milliseconds between internet reachability checks when the internet was previously detected. Only used on platforms which do not supply internet reachability natively or if useNativeReachability is false . |
reachabilityRequestTimeout | number | 15 seconds | The number of milliseconds that a reachability check is allowed to take before failing. Only used on platforms which do not supply internet reachability natively or if useNativeReachability is false . |
reachabilityShouldRun | () => boolean | () => true | A function which returns a boolean to determine if checkInternetReachability should be run. |
shouldFetchWiFiSSID | boolean | false | A flag indicating one of the requirements on iOS has been met to retrieve the network (B)SSID, and the native SSID retrieval APIs should be called. This has no effect on Android. |
useNativeReachability | boolean | true | A flag indicating whether or not Netinfo should use native reachability checks, if available. |
Please note the difference between global and isolated usage described here
configure()
Configures the library with the given configuration. You only need to supply the properties which you want to change from the default values.
Note that calling this will stop all previously added listeners from being called again. It is best to call this right when your application is started to avoid issues.
Example:
1NetInfo.configure({ 2 reachabilityUrl: 'https://clients3.google.com/generate_204', 3 reachabilityTest: async (response) => response.status === 204, 4 reachabilityLongTimeout: 60 * 1000, // 60s 5 reachabilityShortTimeout: 5 * 1000, // 5s 6 reachabilityRequestTimeout: 15 * 1000, // 15s 7 reachabilityShouldRun: () => true, 8 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID. Will leak memory if set to true without meeting requirements. 9 useNativeReachability: false 10});
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:
1// Subscribe 2const unsubscribe = NetInfo.addEventListener(state => { 3 console.log("Connection type", state.type); 4 console.log("Is connected?", state.isConnected); 5}); 6 7// Unsubscribe 8unsubscribe();
useNetInfo()
A React Hook which can be used to get access to the latest state from the global instance. It returns a hook with the NetInfoState
type.
Example:
1import {useNetInfo} from "@react-native-community/netinfo"; 2 3const YourComponent = () => { 4 const netInfo = useNetInfo(); 5 6 return ( 7 <View> 8 <Text>Type: {netInfo.type}</Text> 9 <Text>Is Connected? {netInfo.isConnected?.toString()}</Text> 10 </View> 11 ); 12};
You can optionally send configuration when setting up the hook. Note that configuration is global for the library, so you shouldn't send different configuration for different hooks. It is instead recommended that you called NetInfo.configure()
once when your project starts. The hook option is only provided as a convinience.
1const YourComponent = () => {
2 const netInfo = useNetInfo({
3 reachabilityUrl: 'https://clients3.google.com/generate_204',
4 reachabilityTest: async (response) => response.status === 204,
5 reachabilityLongTimeout: 60 * 1000, // 60s
6 reachabilityShortTimeout: 5 * 1000, // 5s
7 reachabilityRequestTimeout: 15 * 1000, // 15s
8 reachabilityShouldRun: () => true,
9 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID
10 useNativeReachability: false
11 });
12
13 // ...
14};
fetch()
Returns a Promise
that resolves to a NetInfoState
object.
Example:
1NetInfo.fetch().then(state => { 2 console.log("Connection type", state.type); 3 console.log("Is connected?", state.isConnected); 4});
You can optionally send an interface
string so the Promise
resolves to a NetInfoState
from the NetInfoStateType
indicated in interface
argument.
1NetInfo.fetch("wifi").then(state => { 2 console.log("SSID", state.details.ssid); 3 console.log("BSSID", state.details.bssid); 4 console.log("Is connected?", state.isConnected); 5});
refresh()
Updates NetInfo's internal state, then returns a Promise
that resolves to a NetInfoState
object. This is similar to fetch()
, but really only useful on platforms that do not supply internet reachability natively. For example, you can use it to immediately re-run an internet reachability test if a network request fails unexpectedly.
Example:
1NetInfo.refresh().then(state => { 2 console.log("Connection type", state.type); 3 console.log("Is connected?", state.isConnected); 4});
This will also update subscribers using addEventListener
and/or useNetInfo
.
Please note the difference between global and isolated usage described here
useNetInfoInstance()
A React Hook which can be used to create and manage an isolated instance of a network manager class. It returns a refresh
function and the current NetInfoState
.
Example:
1import { useNetInfoInstance } from "@react-native-community/netinfo"; 2 3const YourComponent = () => { 4 const {netInfo, refresh} = useNetInfoInstance(); 5 6 return ( 7 <View> 8 <Text>Type: {netInfo.type}</Text> 9 <Text>Is Connected? {netInfo.isConnected?.toString()}</Text> 10 </View> 11 ); 12};
isPaused: You can also pause the hooks internal network checks by passing a boolean value true
as the first argument.
configuration: You can optionally send configuration as the second argument when setting up the hook. Note that configuration is local to the instance managed by this hook and has no relation to the configuration passed to other functions configure()
or useNetInfo()
;
1import { useNetInfoInstance } from "@react-native-community/netinfo"; 2 3const YourComponent = () => { 4 const isPaused = false; 5 const config = { 6 reachabilityUrl: 'https://clients3.google.com/generate_204', 7 reachabilityTest: async (response) => response.status === 204, 8 reachabilityLongTimeout: 60 * 1000, // 60s 9 reachabilityShortTimeout: 5 * 1000, // 5s 10 reachabilityRequestTimeout: 15 * 1000, // 15s 11 reachabilityShouldRun: () => true, 12 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID 13 useNativeReachability: false 14 } 15 16 const { netInfo } = useNetInfoInstance(isPaused, config); 17 //...
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:
1setupFiles: ['<rootDir>/jest.setup.js']
You should then add the following to your Jest setup file to mock the NetInfo Native Module:
1import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js'; 2 3jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
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.
The SCNetworkReachability API used in iOS does not send events to the app in the background, so switching from one Wi-Fi network to another when your App was in background will not send an event and your network state will be out of sync with device state. To be sure you have up to date status when your app is in foreground again, you should re-fetch state each time when App comes to foreground, something like this:
1 useEffect(() => {
2 const subAppState = AppState.addEventListener("change", async (nextAppState) => {
3 if (IS_IOS_DEVICE && nextAppState=='active') {
4 let newNetInfo = await NativeModules.RNCNetInfo.getCurrentState('wifi');
5 //your code here
6 }
7 });
8 const unsubNetState = NetInfo.addEventListener(state => {
9 //your code here
10 });
11 return () => {
12 if (subAppState) {
13 subAppState.remove();
14 }
15 unsubNetState();
16 };
17 },[]);
Please see the contributing guide.
The library is released under the MIT license. For more information see LICENSE
.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
binaries present in source code
Details
Reason
7 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 5
Reason
Found 13/30 approved changesets -- score normalized to 4
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
107 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More@rescript-react-native/netinfo
ReScript bindings for @react-native-community/netinfo.
@react-native-community/cli-config
This package is part of the [React Native CLI](../../README.md). It contains commands for managing the configuration of React Native app.
@react-native-community/cli-doctor
This package is part of the [React Native CLI](../../README.md). It contains commands for diagnosing and fixing common Node.js, iOS, Android & React Native issues.
@react-native-community/cli
React Native CLI