React Native AsyncStorage — Complete Guide
In this tutorial, you'll learn about React Native AsyncStorage. We cover key concepts, practical examples, and best practices.
The Problem
AsyncStorage is slow for frequent writes, or your stored data returns null after deserialization.
Wrong Approach ❌
// Storing without JSON serialization
await AsyncStorage.setItem('user', userObject); // [object Object] stored!
// Frequent writes in a loop
for (const item of items) {
await AsyncStorage.setItem(`item_${item.id}`, JSON.stringify(item));
}
Output: [object Object] saved. Multiple slow async writes.
Right Approach ✅
import AsyncStorage from '@react-native-async-storage/async-storage';
class StorageService {
// JSON-safe operations
static async setObject(key: string, value: any): Promise<void> {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem(key, jsonValue);
} catch (e) {
console.error('Storage set error:', e);
}
}
static async getObject<T>(key: string): Promise<T | null> {
try {
const jsonValue = await AsyncStorage.getItem(key);
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
console.error('Storage get error:', e);
return null;
}
}
static async setString(key: string, value: string): Promise<void> {
await AsyncStorage.setItem(key, value);
}
static async getString(key: string): Promise<string | null> {
return AsyncStorage.getItem(key);
}
// Batch operations
static async setMultiple(pairs: [string, any][]): Promise<void> {
const kvPairs = pairs.map(([key, value]) => [key, JSON.stringify(value)]);
await AsyncStorage.multiSet(kvPairs);
}
static async getMultiple(keys: string[]): Promise<Record<string, any>> {
const pairs = await AsyncStorage.multiGet(keys);
const result: Record<string, any> = {};
pairs.forEach(([key, value]) => {
if (value != null) result[key] = JSON.parse(value);
});
return result;
}
// Remove
static async remove(key: string): Promise<void> {
await AsyncStorage.removeItem(key);
}
static async clear(): Promise<void> {
await AsyncStorage.clear();
}
// Get all keys
static async getAllKeys(): Promise<string[]> {
return AsyncStorage.getAllKeys();
}
// Size limit check
static async getSize(key: string): Promise<number> {
const value = await AsyncStorage.getItem(key);
return value ? value.length : 0;
}
}
// Migration to MMKV (much faster)
// npm install react-native-mmkv
import { MMKV } from 'react-native-mmkv';
const storage = new MMKV({
id: 'app-storage',
encryptionKey: 'optional-key',
});
// MMKV is synchronous and 30x faster
storage.set('user', JSON.stringify(user));
const userData = JSON.parse(storage.getString('user') ?? '{}');
// Migration helper
async function migrateToMMKV() {
const keys = await AsyncStorage.getAllKeys();
const pairs = await AsyncStorage.multiGet(keys);
pairs.forEach(([key, value]) => {
if (value) storage.set(key, value);
});
await AsyncStorage.clear();
}
Output: Properly serialized storage with batch operations.
Prevention
- Always serialize objects with
JSON.stringify/parse. - Use
multiSet/multiGetfor batch operations. - Avoid storing large objects (> 100KB) in AsyncStorage.
- Migrate to MMKV for performance-critical storage.
- Use
encryptionKeyfor sensitive data in MMKV.
Common Mistakes with native async storage
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro