Persistent Local Storage
8 min read
Welcome! If you are building an app, eventually, you will need it to remember things.
Imagine you are running a pizza shop. You have customers coming in constantly. If you, the chef, forget where you put the cheese every time a new customer walks in, you are going to have a bad time. You need a way to remember things—inventory, recipes, and the cash register balance—even after you close the shop for the night and return the next morning.
In the mobile app world, if your app forgets who the user is or what theme they selected the moment they close the app, they will uninstall it faster than you can say "pineapple on pizza." We solve this using Persistent Local Storage.
In this guide, we will progress from saving simple text to securing sensitive tokens, organizing large datasets, and finally handling raw files.
1. Simple Key-Value Storage with AsyncStorage
The Problem
By default, the memory in your React Native app is volatile. If you store the user's preferred app theme (e.g., "dark mode") in a React state variable, that data is destroyed the second the app is closed.
The Solution
AsyncStorage is an asynchronous, unencrypted, persistent key-value storage system.
It solves the memory problem by writing string data to the device's local storage. When the user opens the app again, you can look up the value using its specific "key". It is the industry standard for saving non-sensitive, simple data like user preferences, feature flags, or onboarding completion status.
Installation
Always use the community package (the core React Native one is deprecated):
npx expo install @react-native-async-storage/async-storageIndustry Practice & Usage
AsyncStorage can only store strings. If you want to store a JavaScript object or array, you must convert it to a string first using JSON.stringify(), and convert it back using JSON.parse() when reading it.
Here is a practical helper file you might see in a production codebase:
// utils/storage.ts
import AsyncStorage from '@react-native-async-storage/async-storage';
// 1. Storing data
export const storeThemePreference = async (theme: string) => {
try {
await AsyncStorage.setItem('app_theme', theme);
} catch (error) {
console.error('Error saving theme:', error);
}
};
// 2. Storing complex objects
export const storeUserProfile = async (userObject: object) => {
try {
const jsonValue = JSON.stringify(userObject);
await AsyncStorage.setItem('user_profile', jsonValue);
} catch (error) {
console.error('Error saving user profile:', error);
}
};
// 3. Retrieving data
export const getUserProfile = async () => {
try {
const jsonValue = await AsyncStorage.getItem('user_profile');
// If the value exists, parse it back to an object. Otherwise, return null.
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (error) {
console.error('Error reading user profile:', error);
}
};
// 4. Deleting data
export const removeUserProfile = async () => {
try {
await AsyncStorage.removeItem('user_profile');
} catch (error) {
console.error('Error removing user profile:', error);
}
};Fun Fact: AsyncStorage is literally just saving a plain text file on the user's phone. Do not put passwords in here. Hackers with a USB cable and some free time can easily read it!
2. Protecting Sensitive Data using Expo SecureStore
The Problem
As mentioned above, AsyncStorage is entirely unencrypted. If your app requires a user to log in, you will usually receive an Authentication Token (JWT) from your server. If you store this token in AsyncStorage, malicious apps or users with rooted/jailbroken devices can extract it and steal the user's session.
The Solution
Expo SecureStore provides a way to encrypt and securely store key-value pairs locally on the device.
Under the hood, it uses the heavily guarded Keychain on iOS and Keystore on Android. It acts exactly like AsyncStorage but wraps your data in military-grade encryption. It is the absolute industry standard for storing Authentication tokens, passwords, and sensitive API keys.
Installation
npx expo install expo-secure-storeIndustry Practice & Usage
SecureStore is incredibly easy to use, but it has a limitation: it is only meant for small pieces of data. Historically, iOS Keychain limits entries to roughly 2048 bytes. Do not try to store an entire user database in SecureStore.
import * as SecureStore from 'expo-secure-store';
// Saving a sensitive auth token
export async function saveAuthToken(token: string) {
try {
await SecureStore.setItemAsync('secure_user_token', token);
console.log('Token secured locked away! 🔒');
} catch (error) {
console.error('Failed to secure token:', error);
}
}
// Retrieving the token for an API call
export async function getAuthToken() {
try {
const token = await SecureStore.getItemAsync('secure_user_token');
if (token) {
return token;
} else {
console.log('No token found. User needs to log in.');
return null;
}
} catch (error) {
console.error('Failed to get token:', error);
}
}
// Removing the token (Logging out)
export async function deleteAuthToken() {
await SecureStore.deleteItemAsync('secure_user_token');
}3. Relational Local Data: Setting up Expo SQLite
The Problem
Imagine you are building an offline-first inventory app. You need to store 10,000 products. If you use AsyncStorage, you have to read a massive 15MB JSON string into memory, parse it, search for the item, and then save the entire 15MB string back just to update the price of one single apple. Your app will freeze, and your user's battery will drain rapidly.
The Solution
Expo SQLite gives your app access to a local relational database that can be queried through SQL.
It solves the problem by allowing you to search, filter, and update massive datasets efficiently without loading everything into the device's active memory at once. It is perfect for POS (Point of Sale) systems, offline-first architectures, and complex relational data.
Installation
npx expo install expo-sqliteIndustry Practice & Usage
Recent updates to Expo SQLite (SDK 50+) introduced a modern, asynchronous API. The standard practice is to wrap your application in a SQLiteProvider which automatically handles opening the database and running migrations, and then consuming it via a hook.
Step 1: Wrap your App with the Provider
// App.tsx
import { SQLiteProvider } from 'expo-sqlite';
import { Text, View } from 'react-native';
import MainScreen from './MainScreen';
// A simple function to create tables if they don't exist
async function initializeDatabase(db: any) {
await db.execAsync(`
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);
`);
}
export default function App() {
return (
<SQLiteProvider databaseName="myOfflineDb.db" onInit={initializeDatabase}>
<MainScreen />
</SQLiteProvider>
);
}Step 2: Query the data anywhere in your app
// MainScreen.tsx
import { useSQLiteContext } from 'expo-sqlite';
import { useState, useEffect } from 'react';
import { Button, Text, View } from 'react-native';
export default function MainScreen() {
const db = useSQLiteContext();
const [users, setUsers] = useState([]);
const fetchUsers = async () => {
// getALLAsync retrieves an array of rows
const result = await db.getAllAsync('SELECT * FROM users');
setUsers(result);
};
const addUser = async () => {
// Use prepared statements (?) to prevent SQL Injection!
await db.runAsync('INSERT INTO users (name) VALUES (?)', ['John Doe']);
fetchUsers();
};
useEffect(() => {
fetchUsers();
}, []);
return (
<View style={{ padding: 40 }}>
<Button title="Add User" onPress={addUser} />
{users.map((user, index) => (
<Text key={index}>{user.id} - {user.name}</Text>
))}
</View>
);
}4. Managing Files and Directories with Expo FileSystem
The Problem
You need to download a 50MB PDF menu, cache a user's profile picture, or save an audio recording. You cannot efficiently store heavy binary blobs (images, videos, PDFs) inside AsyncStorage or a SQLite database.
The Solution
Expo FileSystem provides direct read/write access to the device's local file directories.
It allows you to download files directly from the internet to the device's hard drive and reference their local URI. This drastically reduces network usage because you can cache images and documents for offline use.
Installation
npx expo install expo-file-systemIndustry Practice & Usage
The most common industry use-case for the FileSystem is downloading a remote file (like a PDF or Video) into the app's documentDirectory so it can be viewed offline.
import * as FileSystem from 'expo-file-system';
export async function downloadInvoicePDF(invoiceUrl: string, fileName: string) {
try {
// 1. Define where the file should be saved
// FileSystem.documentDirectory is a safe place that the OS won't randomly delete.
const fileUri = `${FileSystem.documentDirectory}${fileName}.pdf`;
console.log('Downloading starting... ⏳');
// 2. Execute the download
const downloadObject = await FileSystem.downloadAsync(invoiceUrl, fileUri);
console.log('Download complete! 🎉 Saved to:', downloadObject.uri);
// You can now pass `downloadObject.uri` to a PDF Viewer or Video Player!
return downloadObject.uri;
} catch (error) {
console.error('Failed to download file:', error);
}
}You can also use FileSystem to read the text of local files:
const fileContent = await FileSystem.readAsStringAsync(fileUri);Pro-Tip: If you are downloading temporary files that you don't care if the OS deletes later (to free up space), save them to
FileSystem.cacheDirectoryinstead ofdocumentDirectory. Keep your users' storage clean!
Further Reading & Official Documentation
Always check the latest documentation for advanced configurations, especially when dealing with native modules or upgrading your Expo SDK version.
Challenge
Challenge: Implement Multi-Storage for an Offline Reading App
You are tasked with building the core storage logic for a new mobile reading list application using Expo. The application must function offline and handle different types of data securely and efficiently.
Your goal is to complete the provided JavaScript functions to correctly implement the following storage requirements:
- User Preferences: The app needs to remember the user's theme choice (e.g.,
{ theme: 'dark' }). This data is not sensitive. Implement functions to save and load this preference object usingAsyncStorage. - API Key: The app uses a third-party service to fetch book data, which requires a sensitive API key. Implement functions to securely save and retrieve this key using
Expo SecureStore. - Book Library: The user's entire library of books (which could be very large) must be stored locally for offline access. Each book has an
id,title,author, and anisReadstatus. Implement functions to add a new book and retrieve all books marked as 'read' from anExpo SQLitedatabase. Assume the database connectiondbis already established and passed to your functions. - Book Covers: To save bandwidth and provide a seamless offline experience, book cover images must be downloaded and cached on the device. Implement a function that downloads an image from a given URL and stores it permanently in the app's local file system using
Expo FileSystem.
Expected result
Your completed code should correctly implement the logic for each function using the appropriate Expo or React Native library as specified.
Correct Implementation Details:
saveUserPreferences(preferences)- Should use
JSON.stringify()to convert thepreferencesobject into a string. - Should call
await AsyncStorage.setItem('user-preferences', stringifiedPreferences);to store the data.
- Should use
loadUserPreferences()- Should call
await AsyncStorage.getItem('user-prefernces');to retrieve the stored string. - It must check if the retrieved value is not
nullbefore attempting to parse it withJSON.parse(). - Should return the parsed object, or
nullif no data was found.
- Should call
saveApiKey(apiKey)- Should call
await SecureStore.setItemAsync('api_key', apiKey);to securely store the key.
- Should call
getApiKey()- Should call
await SecureStore.getItemAsync('api_key');to retrieve the key.
- Should call
addBookToDatabase(db, book)- Should execute an
INSERTSQL statement using prepared statements (placeholders). - The implementation should look similar to:javascript
await db.runAsync( 'INSERT INTO books (id, title, author, isRead) VALUES (?, ?, ?, ?)', [book.id, book.title, book.author, book.isRead ? 1 : 0] );
- Should execute an
getReadBooks(db)- Should execute a
SELECTSQL statement with aWHEREclause. - The implementation should look similar to:javascript
const allReadBooks = await db.getAllAsync('SELECT * FROM books WHERE isRead = 1'); return allReadBooks;
- Should execute a
cacheBookCover(imageUrl, bookId)- Should define the local file destination URI using
FileSystem.documentDirectory.- Example:
const localUri = FileSystem.documentDirectory +${bookId}.jpg;
- Example:
- Should use
await FileSystem.downloadAsync(imageUrl, localUri);to download and save the file. - Should return the
localUristring.
- Should define the local file destination URI using