Local Storage

Article · 2:00

MMKV and AsyncStorage for ordinary data, expo-secure-store for anything that grants access.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

There are three places to put data on the device and the choice is about speed and secrecy.

AsyncStorage is the familiar key-value store. It is asynchronous, backed by SQLite on Android, and fine for preferences. MMKV is the faster alternative - memory-mapped, synchronous, and roughly an order of magnitude quicker - which matters at startup, where reading a handful of keys asynchronously means the first frame renders before the data arrives and then flashes when it does. A synchronous read removes that flash entirely.

Neither is encrypted. expo-secure-store is, and it is where tokens go: it writes to the iOS Keychain and to Android's EncryptedSharedPreferences, both protected by the device's own key storage. The constraint to know about is size - it is intended for small values, so store the token there and the user profile elsewhere.

The rule is the same as on any platform. If losing it would be an inconvenience, AsyncStorage or MMKV. If someone else having it would be a breach, SecureStore. An access token in AsyncStorage is a finding in any security review.

TS Example 1 39 lines
import { MMKV } from 'react-native-mmkv';
import * as SecureStore from 'expo-secure-store';

// Fast, synchronous, and therefore readable during the first render.
const storage = new MMKV();

export const preferences = {
  getTheme(): string {
    // No await - so the first frame already has the right theme.
    return storage.getString('theme') ?? 'system';
  },
  setTheme(theme: string) {
    storage.set('theme', theme);
  },
  getLastSync(): number {
    return storage.getNumber('lastSync') ?? 0;
  },
};

// Encrypted: the iOS Keychain, and EncryptedSharedPreferences on Android.
const ACCESS_TOKEN = 'accessToken';

export const tokens = {
  async save(token: string) {
    await SecureStore.setItemAsync(ACCESS_TOKEN, token, {
      keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
    });
  },
  async read(): Promise<string | null> {
    return SecureStore.getItemAsync(ACCESS_TOKEN);
  },
  async clear() {
    // Signing out means deleting it, not just clearing a variable.
    await SecureStore.deleteItemAsync(ACCESS_TOKEN);
  },
};

// Wrong, and common: a token in unencrypted storage.
// storage.set('accessToken', token);   // <- a finding in any review

Open this example in the editor and change it. Nothing you type is saved.