Learn React Native ยท 11/15

Local Data & Offline Capabilities

6 min read

Local Data & Offline Capabilities in React Native ๐Ÿ“ฒ

Welcome! In the world of mobile apps, a seamless user experience is king. But what happens when the internet connection is as flaky as a croissant? ๐Ÿฅ Your app shouldn't just throw up its hands and display a dreaded loading spinner. This is where local data storage and offline capabilities come to the rescue, allowing your app to function reliably, with or without a network connection.

This guide will walk you through the essential tools and strategies to make your React Native apps robust and user-friendly, even when they're offline.


1. AsyncStorage: Saving Simple User Preferences ๐Ÿ“

The Problem: Your app needs to remember small, non-sensitive pieces of information across restarts. Think of things like user settings (e.g., dark mode preference), a "Remember Me" option on a login screen, or the last screen the user visited.

The Solution: AsyncStorage

AsyncStorage is a simple, unencrypted, asynchronous, key-value storage system that is global to your app. It's perfect for storing small amounts of data that don't need to be secure.

Imagine your app has a little notepad. You can write down a note (the "value") and give it a label (the "key"). Later, you can look up that label and read the note. That's essentially what AsyncStorage does.

Installation:

First, you'll need to install the community-maintained package:

bash
npm install @react-native-async-storage/async-storage

Common Usage:

Let's say we want to save a user's chosen theme.

javascript
import AsyncStorage from '@react-native-async-storage/async-storage';

// ๐Ÿ’พ Storing data
const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('user-theme', value);
  } catch (e) {
    // saving error
  }
};

// ๐Ÿ“– Reading data
const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('user-theme');
    if (value !== null) {
      // value previously stored
    }
  } catch (e) {
    // error reading value
  }
};

Important Note: AsyncStorage only stores string data. If you want to store an object, you'll need to JSON.stringify() it before saving and JSON.parse() it after retrieving.

Industry Practice: While great for simple data, remember that AsyncStorage is not secure. Anyone with access to the phone's file system can potentially read this data. Never store sensitive information like passwords or API keys here.


2. SecureStore: Keeping Sensitive Data Safe (Tokens) ๐Ÿ”

The Problem: Your app handles sensitive information, like authentication tokens, API keys, or user credentials. Storing this in AsyncStorage is a major security risk. You need a secure vault.

The Solution: SecureStore

SecureStore (from the Expo SDK) provides a way to store data securely on the device. It uses the native Keychain services on iOS and Keystore on Android to encrypt the data, making it much safer.

Think of SecureStore as a locked safe. You put your valuable items inside, and only your app has the key to open it.

Installation (for Expo projects):

bash
npx expo install expo-secure-store

Common Usage:

Hereโ€™s how you would securely store and retrieve an authentication token:

javascript
import * as SecureStore from 'expo-secure-store';

// ๐Ÿ”’ Saving a token
async function saveToken(token) {
  await SecureStore.setItemAsync('authToken', token);
}

// ๐Ÿ”“ Retrieving a token
async function getToken() {
  let token = await SecureStore.getItemAsync('authToken');
  return token;
}

// ๐Ÿ—‘๏ธ Deleting a token
async function deleteToken() {
  await SecureStore.deleteItemAsync('authToken');
}

Industry Practice: SecureStore is the go-to solution for storing sensitive data in Expo-based React Native apps. For bare React Native projects, react-native-keychain is a popular and robust alternative. It's crucial to use these tools to protect your users' data and your application's integrity.


3. SQLite Basics for Complex Local Data ๐Ÿ—ƒ๏ธ

The Problem: Your app needs to store a large amount of structured, relational data. For example, a to-do list app with multiple lists, each containing multiple tasks with due dates and priorities. A simple key-value store like AsyncStorage becomes cumbersome and inefficient for this.

The Solution: SQLite

SQLite is a C-language library that provides a lightweight, disk-based database that doesnโ€™t require a separate server process. It's a full-fledged relational database, meaning you can create tables, define relationships between them, and use SQL queries to manage your data.

Imagine you have a large library of books. Instead of just piling them in a room (AsyncStorage), you organize them on shelves (tables) by genre, author, etc. This makes it much easier to find and manage your books. That's the power of SQLite.

Installation (a popular library):

bash
npm install --save react-native-sqlite-storage

And for iOS, you'll need to install the pods:

bash
cd ios && pod install

Common Usage:

Here's a basic example of creating a "todos" table and adding an item:

javascript
import { openDatabase } from 'react-native-sqlite-storage';

const db = openDatabase({ name: 'MyData.db', location: 'default' });

// Create a table
const createTable = () => {
  db.transaction((tx) => {
    tx.executeSql(
      'CREATE TABLE IF NOT EXISTS todos(id INTEGER PRIMARY KEY AUTOINCREMENT, task TEXT, completed INT(1))',
      [],
      () => { console.log('Table created successfully'); },
      error => { console.log('Error creating table', error); }
    );
  });
};

// Add a new todo
const addTodo = (taskName) => {
  db.transaction((tx) => {
    tx.executeSql(
      'INSERT INTO todos (task, completed) VALUES (?,?)',
      [taskName, 0],
      (tx, results) => {
        if (results.rowsAffected > 0) {
          console.log('Todo added successfully');
        } else {
          console.log('Failed to add todo');
        }
      }
    );
  });
};

Industry Practice: SQLite is excellent for apps that need to manage complex data offline. It's a reliable and powerful choice for building robust, data-driven applications that can function without an internet connection.


4. Designing Apps for Offline-First Usage โœˆ๏ธ

The Concept: An "offline-first" approach means you design your app to work seamlessly without an internet connection from the very beginning. The network is treated as an enhancement for syncing data, not a requirement for the app to function.

Why it Matters: Mobile networks can be unreliable. An offline-first design leads to a better user experience, as the app is always responsive and users can continue their tasks regardless of their connectivity.

Core Principles:

  • Local Database is the Source of Truth: Your UI should always read from and write to the local database first. This makes the app feel instantaneous.
  • Optimistic UI Updates: When a user performs an action (like adding a comment), update the UI immediately from the local data. Don't wait for the server's confirmation.
  • Data Synchronization: Implement a system to sync local changes with the server when the network is available. This can be a simple "pull-to-refresh" or a more complex background sync process.
  • Conflict Resolution: Plan for how to handle situations where data is changed both locally and on the server while the app was offline. A common strategy is the "last write wins" approach.

A Simple Simulation:

Imagine a messaging app.

  1. You're on a plane with no Wi-Fi. โœˆ๏ธ
  2. You write and send a message to a friend.
  3. Offline-First App: The message immediately appears in your chat history (written to the local SQLite database). It might have a small "pending" icon.
  4. Online-Dependent App: You see a loading spinner that never goes away, or an error message. The message is lost.
  5. When you land and reconnect to the internet: The offline-first app detects the connection and syncs your pending message to the server. Your friend receives it, and the "pending" icon disappears.

This seamless experience is the goal of offline-first design.

Interesting Fact: The concept of "offline-first" gained significant traction with the rise of Progressive Web Apps (PWAs), but its principles are crucial for building high-quality native mobile apps as well.


Extra Reading & References ๐Ÿ“š

Challenge

You are tasked with creating a data management service for a new offline-first React Native application. This service will handle user preferences, secure credentials, and provide the necessary database schema for tasks.

Your goal is to implement the UserDataService class with the following functionality:

  1. Import Modules: At the top of the file, import AsyncStorage from '@react-native-async-storage/async-storage' and * as SecureStore from 'expo-secure-store'.
  2. Save User Preferences: Implement an asynchronous method savePreferences(preferences). This method should accept a user preferences object (e.g., { theme: 'dark', notificationsEnabled: true }), stringify it, and store it in AsyncStorage under the key 'user_preferences'.
  3. Retrieve User Preferences: Implement an asynchronous method getPreferences(). This method should retrieve the preferences string from AsyncStorage, parse it back into an object, and return it. If no preferences are found, it should return null.
  4. Save Authentication Token: Implement an asynchronous method saveAuthToken(token). This method must securely store a provided authentication token string using SecureStore with the key 'auth_token'.
  5. Retrieve Authentication Token: Implement an asynchronous method getAuthToken(). This method should retrieve the secure authentication token from SecureStore and return it.
  6. Define Task Table Schema: Implement a static method getTaskTableSchema() that returns a SQL query string. This query must create a table named tasks with the following columns:
    • id: INTEGER, PRIMARY KEY, AUTOINCREMENT
    • title: TEXT, NOT NULL
    • isCompleted: INTEGER, defaulting to 0
    • isSynced: INTEGER, defaulting to 0

Expected result

Your final code should consist of a single UserDataService class definition with all specified methods correctly implemented.

  • The file must begin with the correct import statements for AsyncStorage and SecureStore.
  • The savePreferences method must use AsyncStorage.setItem and JSON.stringify.
  • The getPreferences method must use AsyncStorage.getItem and JSON.parse, handling the case where no item is found.
  • The saveAuthToken and getAuthToken methods must correctly call the asynchronous methods from the SecureStore module (setItemAsync and getItemAsync).
  • The getTaskTableSchema static method must return a valid SQL CREATE TABLE string that exactly matches the schema described in the instructions.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.