How to check internet connection in React Native and show an offline alert
A tutorial on how to check internet connection in React Native for both Android and iOS. Learn how to show an offline alert when the user has no internet.
Yogini Bende
Aug 21, 2024 • 6 min read
In this article, we will dive into the practical steps for checking internet connectivity in React Native applications and displaying an offline alert to the user.
This feature is crucial for enhancing user experience, especially in mobile applications where internet connectivity can be intermittent. We'll cover everything from setting up your environment to implementing and testing the functionality.
Table of Contents
Introduction
React Native is a popular framework for developing cross-platform mobile applications using JavaScript. It allows developers to create native-like apps for both iOS and Android platforms. One common requirement for every mobile app is the ability to detect internet connectivity and inform users when they are offline. This article will walk you through the process of implementing this feature in a React Native app.
Prerequisites
Before starting, you should have the following:
Basic knowledge of React Native and JavaScript.
Node.js and npm/yarn installed on your machine.
React Native CLI installed, or you can use Expo CLI if you prefer.
An initialized React Native project.
Step 1: Set Up Your React Native Environment
If you haven't already, start by setting up a new React Native project. You can do this using the React Native CLI or Expo. For the purpose of this article, we'll use the React Native CLI. We will create a
npx react-native init OfflineAlertApp
cd OfflineAlertApp
Step 2: Using the NetInfo Library
To check internet connectivity in React Native, we'll use the @react-native-community/netinfo library, which provides an easy-to-use API for this purpose. This is an open-source npm package that is part of the React Native Community. It allows you to subscribe to network state changes and get information about the current network status. You can install the library by running the following npm command. Alternatively, you can use Yarn if you prefer.
npm install @react-native-community/netinfo
Step 3: Implementing the Internet Connectivity Check
First, import the NetInfo library in your App component or wherever you plan to handle the connectivity check.
import NetInfo from '@react-native-community/netinfo';
Next, create a function to check the internet connection. This function subscribes to network state changes and updates the component's state accordingly.
import React, { useEffect, useState } from 'react';
import { View, Text, Alert } from 'react-native';
const App = () => {
const [isConnected, setConnected] = useState(true);
useEffect(() => {
const unsubscribe = NetInfo.addEventListener((state) => {
setConnected(state.isConnected);
if (!state.isConnected) {
showAlert();
}
});
return () => {
unsubscribe();
};
}, []);
const showAlert = () => {
Alert.alert(
'Internet Connection',
'You are offline. Some features may not be available.'
);
};
return (
<View>{isConnected ? <Text>Online</Text> : <Text>Offline</Text>}</View>
);
};
export default App;
Step 4: Displaying an Offline Alert
The showAlert function in the code above is triggered whenever the internet connection goes offline. It uses the Alert component from React Native to display an offline notification to the user. You can customize this alert based on your application's design requirements.
For e.g. in Peerlist Mobile App, we show a bottom sheet with a message when the user is offline. Something like this -
Step 5: Testing Your Implementation
To test your implementation, you can use an Android or iOS emulator, or a physical device. Turn off the internet connection on the device or emulator to see the offline alert in action. You can also use the React Native Debugger or the console logs to debug and view the connectivity status changes in real-time.
Handling Possible Errors and Their Solutions
When implementing internet connectivity checks in React Native, you might encounter several errors or issues. Here's a list of common problems and how to address them:
1. Error: Installation fails or the app does not recognize the NetInfo library.
Ensure you've correctly installed @react-native-community/netinfo. If you encounter errors, try cleaning your project's cache with npm cache clean --force
or yarn cache clean
, then reinstall the packages. For linking issues in older React Native versions (below 0.60), manually link the library with react-native link @react-native-community/netinfo
.
2. Incorrect Usage of Hooks - Hook rules violations, such as calling hooks inside loops, conditions, or nested functions.
Always use hooks at the top level of your React function components. Do not call hooks inside loops, conditions, or nested functions to ensure they are called in the same order each time the component renders.
3. Network State Changes Not Detected - The app does not respond to network state changes.
Ensure the event listener for network state changes is set up correctly in the useEffect hook and that the unsubscribe function is called on component unmount to avoid memory leaks and ensure that your app correctly detects network changes.
4. Alert Does Not Show - The offline alert does not display when the app goes offline.
Verify that the showAlert function is correctly defined and called within the network state change event handler. Also, check that the Alert import from react-native is correctly done. Remember, alerts may behave differently on iOS and Android in terms of appearance or user interaction.
5. App Performance Issues or lag when checking for internet connectivity.
Optimize your network state change handler. Avoid setting state or showing alerts unnecessarily. For instance, you can check if the connectivity status has actually changed before updating the state or showing an alert to prevent unnecessary re-renders or alerts.
6. App crashes on startup after implementing the connectivity check.
This could be due to an unhandled promise rejection or an error in the way the NetInfo event listener is set up. Ensure all promises are properly handled with .catch() blocks. Also, review the setup of your network state change listener to ensure it does not cause any crashes.
Bonus: React Native Jobs
If you are looking for a job in React Native, check out the these jobs on Peerlist. You can also post your job openings for free!
Conclusion
That's it! Implementing an internet connectivity check in React Native is straightforward with the NetInfo library. This enhances the user experience by providing timely notifications about the network status. It also allows developers to handle offline scenarios more effectively. Makse sure to test your application under various network conditions to ensure reliability and a seamless user experience. If you have any questions or feedback, feel free to reach out. Happy coding!