Skip to main content

Working with Network Connectivity

1. Checking Network Status

Property Description Values
isConnected Indicates if the device is connected to a network true or false
type Network type (e.g., cellular, wifi) 'cellular', 'wifi', 'none'
isInternetReachable Indicates if the device can reach the internet true or false

Example: Check Network Status

import * as Network from 'expo-network';

const checkNetworkStatus = async () => {
  const { isConnected, type, isInternetReachable } = await Network.getNetworkStateAsync();
  console.log('Connected:', isConnected);
  console.log('Type:', type);
  console.log('Internet Reachable:', isInternetReachable);
};

checkNetworkStatus();

2. Monitoring Network Changes

Example: Listen for network status changes

import { Network } from 'expo-network';

Network.addEventListener('networkStatusChange', (status) => {
  console.log('Network status changed:', status);
});

// Get initial network status
Network.getNetworkStatusAsync().then(status => {
  console.log('Initial network status:', status);
});
Property Description Values
isConnected Indicates if the device is connected to a network true or false
type Network type (e.g., cellular, wifi) "cellular", "wifi", "none"
isConnectionExpensive Indicates if the current connection is expensive (e.g., cellular) true or false
isConnectionVulnerable Indicates if the current connection is not secure (e.g., public WiFi) true or false
Note: On Android, isConnectionVulnerable is only available on API level 23+.
Warning: On iOS, Network module does not work in the Expo Go app. You need to build a standalone app.

3. Detecting Connection Type

Property Description Values
connectionType Indicates the type of network connection "bluetooth", "cellular", "ethernet", "wifi", "unknown"
isConnected Boolean indicating if device has internet access true, false
isInternetReachable Indicates if device can reach the internet true, false

Example: Check Connection Type

import { Network } from "expo-network";

const checkConnection = async () => {
  const { connectionType, isConnected } = await Network.getNetworkStateAsync();
  console.log("Connection Type:", connectionType);
  console.log("Is Connected:", isConnected);
};

checkConnection();
Note: The connectionType value may vary depending on the device and OS version.

4. Handling Offline Mode

Property Description Default
isConnected Indicates if the device is connected to the internet true
isInternetReachable Checks if the device can reach the internet true

Example: Check Network Status

import { Network } from 'expo-network';

const checkNetworkStatus = async () => {
  const { isConnected, isInternetReachable } = await Network.getNetworkStateAsync();
  console.log('Connected:', isConnected);
  console.log('Internet Reachable:', isInternetReachable);
};

checkNetworkStatus();

Example: Handle Offline Mode

import { Network } from 'expo-network';
import { useEffect, useState } from 'react';

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

  useEffect(() => {
    const checkConnection = async () => {
      const state = await Network.getNetworkStateAsync();
      setIsConnected(state.isConnected);
    };

    checkConnection();
    const listener = Network.addEventListener('networkStateChange', checkConnection);
    return () => listener.remove();
  }, []);

  return isConnected;
};

export default useNetworkStatus;
Note: The isInternetReachable property may return true even if the device is not connected to the internet, as it only checks for reachability to a known server.
Warning: Network API is not available in all environments (e.g., bare React Native projects without Expo). Ensure compatibility before use.

5. Implementing Retry Logic

Example: Basic Retry Logic with Exponential Backoff

import { Network } from 'expo-network';

async function fetchWithRetry(url, maxRetries = 3) {
  let lastError;
  
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return await response.json();
    } catch (error) {
      lastError = error;
      if (attempt === maxRetries) break;
      
      // Exponential backoff
      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  
  throw lastError;
}

// Usage
fetchWithRetry('https://api.example.com/data')
  .then(data => console.log(data))
  .catch(error => console.error('Failed after retries:', error));
Property Description Default Value
maxRetries Maximum number of retry attempts 3
backoffStrategy Retry delay strategy (e.g., exponential) 'exponential'
retryOn HTTP status codes to retry on [429, 503]
Note: Retry logic should be used carefully to avoid overwhelming the server or client resources.
Warning: Implementing retry logic without proper limits can lead to infinite loops or excessive resource consumption.

Best Practices for Retry Logic

  • Implement exponential backoff to prevent server overload
  • Limit the number of retry attempts to avoid indefinite loops
  • Only retry on transient errors (e.g., 429, 503) rather than client errors (4xx)
  • Log retry attempts for debugging and monitoring

6. Using Network Information API

Property Description Values
type Indicates the type of network connection bluetooth, cellular, ethernet, wifi, wimax, none, unknown
downlink Estimated downlink bandwidth in Mbps 1.5, 5, 20
effectiveType Effective connection type based on network characteristics slow-2g, 2g, 3g, 4g

Example: Check network type

import * as Network from &#x27;expo-network&#x27;;

const networkType = await Network.getNetworkTypeAsync();
console.log(networkType); // "wifi", "cellular", etc.

Example: Monitor connection changes

import * as Network from &#x27;expo-network&#x27;;

Network.addEventListener(&#x27;connectionChange&#x27;, (connectionInfo) => {
  console.log(&#x27;Connection type changed to:&#x27;, connectionInfo.type);
});
Note: The Network Information API is not available in all environments. Always check for support before using it.

7. Checking Internet Reachability

Property Description Example
isInternetReachable Indicates whether the device has internet access true or false
isConnected Indicates whether the device is connected to a network true or false

Example: Check Internet Reachability

import { isInternetReachable } from 'expo-network';

const checkConnection = async () => {
  const isReachable = await isInternetReachable();
  console.log('Internet reachable:', isReachable);
};

checkConnection();
Note: isInternetReachable performs a DNS lookup to verify connectivity, which may take a moment.
Warning: This API is not available in all environments (e.g., bare React Native). Ensure compatibility before use.

8. Handling Connection Loss

Example: Detecting and Responding to Connection Loss

import * as Network from &#x27;expo-network&#x27;;

// Check initial connection status
const { isInternetReachable, isConnectionExpensive } = await Network.getNetworkStateAsync();

console.log("Is internet reachable:", isInternetReachable);
console.log("Is connection expensive:", isConnectionExpensive);

// Listen for changes in network state
Network.addEventListener("networkStateChange", (state) => {
  if (!state.isInternetReachable) {
    console.log("No internet connection");
    // Show offline UI or retry logic
  } else {
    console.log("Internet connection restored");
    // Resume normal operations
  }
});
Property Description Values
isInternetReachable Indicates if the device has internet access true / false
isConnectionExpensive Indicates if the current connection is expensive (e.g. cellular) true / false
isConnectionOffline Indicates if the device is offline true / false
Note: The isInternetReachable property may return true even when the device is connected to a network that does not have internet access (e.g., captive portal).
Warning: On some platforms, isConnectionExpensive might not be accurate and should be used as a hint rather than a definitive indicator.

Best Practices for Handling Connection Loss

  • Implement a retry mechanism with exponential backoff when reconnection is attempted.
  • Display user-friendly offline messages or UI elements to indicate connection loss.
  • Cache data locally when offline and sync once the connection is restored.
  • Use Network.addEventListener to listen for real-time network state changes.

9. Queuing Offline Requests

When a device is offline, Expo provides mechanisms to queue network requests and retry them once connectivity is restored. This ensures that users can continue interacting with the app even when offline, and their actions are not lost.

Property Description Default Value
offlineQueue Enables queuing of network requests when offline. false
retryInterval Time (in milliseconds) to wait before retrying queued requests. 5000
maxRetries Maximum number of retry attempts for queued requests. 3

Example: Queuing Offline Requests

import * as Network from 'expo-network';

const queue = [];

function queueRequest(request) {
  if (Network.isInternetReachable === false) {
    queue.push(request);
    console.log('Request queued for later execution.');
  } else {
    executeRequest(request);
  }
}

function retryQueuedRequests() {
  while (queue.length > 0) {
    const request = queue.shift();
    executeRequest(request);
  }
}

function executeRequest(request) {
  fetch(request.url, request.options)
    .then(response => response.json())
    .then(data => console.log('Request executed:', data))
    .catch(error => console.error('Request failed:', error));
}
Note: The expo-network package is used to check for internet reachability. Ensure it's installed and configured correctly in your project.

10. Syncing Data on Reconnection

Example: Basic Data Sync on Network Reconnect

// Check network status and sync data
import * as Network from 'expo-network';

async function handleNetworkChange() {
  const { isInternetReachable, isConnected } = await Network.getNetworkStateAsync();
  
  if (isConnected && isInternetReachable) {
    // Sync local data with remote server
    await syncLocalData();
  }
}

// Listen for network changes
Network.addEventListener('networkStateChange', handleNetworkChange);
Property Description Values
isConnected Indicates if device is connected to a network true / false
isInternetReachable Indicates if device can reach the internet true / false
connectionType Type of network connection (WiFi, cellular) WIFI, CELLULAR, UNKNOWN
Note: Use isInternetReachable to determine if the device can reach the internet, which is more reliable than just isConnected.

Example: Sync with Retry Logic

async function syncLocalData() {
  const maxRetries = 3;
  let retries = 0;

  while (retries < maxRetries) {
    try {
      // Attempt to sync with server
      await fetch('https://api.example.com/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(localData),
      });
      break; // Success, exit loop
    } catch (error) {
      retries++;
      if (retries >= maxRetries) {
        console.error('Sync failed after ' + maxRetries + ' attempts');
      }
    }
  }
}

Syncing Data on Reconnection - Key Points

  • Use expo-network to detect network state changes
  • Sync only when isConnected and isInternetReachable are true
  • Implement retry logic for failed sync attempts
  • Consider using background tasks for data synchronization

Was this article helpful?