Ensuring network connectivity awareness is crucial for a seamless mobile app experience. In React Native, you can achieve this using the @react-native-community/netinfo library. Follow these steps to integrate NetInfo into your React Native application:

Step 1: Install the NetInfo Library

npm install @react-native-community/netinfo

Step 2: Import NetInfo in Your Component

import React, { useState, useEffect } from 'react';
import { LogBox } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import YourMainComponent from './YourMainComponent'; // Import your main component

const App = () => {
  const [isConnected, setIsConnected] = useState(true);

  useEffect(() => {
    // Ignore certain logs and disable all logs for a cleaner console
    LogBox.ignoreLogs(['Animated: `useNativeDriver`']);
    LogBox.ignoreAllLogs(true);

    // Set up NetInfo event listener to track network connectivity changes
    const unsubscribe = NetInfo.addEventListener(state => {
      setIsConnected(state.isConnected);
    });

    // Cleanup function to unsubscribe when the component is unmounted
    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <>
      {/* Pass the network connectivity state to your main component */}
      <YourMainComponent isConnected={isConnected} />
    </>
  );
};

export default App;

Step 3: Integrate Network Status into Your Main Component

In your main component (YourMainComponent), use the isConnected prop to conditionally render content based on the network status:

import React from 'react';
import { View, Text } from 'react-native';

const YourMainComponent = ({ isConnected }) => {
  return (
    <View>
      <Text>{isConnected ? 'Online' : 'Offline'}</Text>
      {/* Add your main component content here */}
    </View>
  );
};

export default YourMainComponent;

By following these steps, you’ve successfully implemented network connectivity awareness, allowing your React Native app to adapt dynamically based on the device’s online or offline status.

Tagged in: