Course contentsShow
← React Native
Lesson 219 of 1,5553. Core Primitive ComponentsFree lesson

Building Offline-First UI

Learners will handle states where network connectivity is missing or inconsistent.

Building Offline-First UI

In this lesson, you will learn how to provide a seamless user experience by ensuring your app remains functional even when the device loses its internet connection.

The Offline-First Mindset

When building mobile apps, you cannot assume the user always has a perfect Wi-Fi or cellular signal. An "offline-first" approach means your application is designed to retrieve data from local storage—which we covered in our previous lessons—before attempting to reach a remote server.

When the network is unavailable, instead of showing a blank screen or a generic error, your app should serve the cached data it already has. The user can interact with the app, and you can queue their actions to sync with the server once the connection is restored.

Detecting Connectivity

To manage this state, you need to know when the network is online or offline. You can listen for connectivity changes and adjust your UI accordingly. For example, if the network drops, you might show a small notification banner or disable the "Submit" button to prevent errors.

import { useEffect, useState } from 'react';
import { View, Text, NetInfo } from 'react-native';

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

  useEffect(() => {
    // Listen for network state changes
    const unsubscribe = NetInfo.addEventListener(state => {
      setIsConnected(state.isConnected);
    });
    return () => unsubscribe();
  }, []);

  if (isConnected) return null;

  return (
    <View style={{ backgroundColor: 'red' }}>
      <Text>You are currently offline. Showing cached content.</Text>
    </View>
  );
};

By displaying this banner, you provide immediate feedback to the user, letting them know that the data they see might not be perfectly up-to-date. This builds trust, as the user understands why the content isn't refreshing. When the connection returns, you can use your persistent storage layer to push any queued updates back to your API, keeping the experience consistent and reliable.

Key Takeaway: An offline-first UI relies on local storage to maintain functionality during connectivity gaps and uses network listeners to provide clear feedback to the user.