Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 71 ยท State and Data

Storing Data: AsyncStorage, MMKV and SecureStore

Keep data on the device in React Native: AsyncStorage, MMKV and SecureStore compared, JSON serialization, what is safe to store, and schema migrations.

When the user closes your app and opens it again, every variable is gone. Anything that must survive, such as a chosen theme, a draft message, an onboarding flag or a login token, has to be written to the device's storage. React Native has no built-in storage API, but three libraries cover the common needs: AsyncStorage for general key-value data, MMKV when you need speed, and SecureStore for secrets.

Choosing the right one is mostly about answering two questions: how sensitive is the data, and how much of it is there? This lesson explains each option, how to serialize values safely, and how to change the stored format in a later app release without breaking existing users.

What runs on this site. These libraries use native code (the phone's file system, Keychain and Keystore), so their code is read-only here. The runnable examples use a stand-in: an in-memory adapter with the same asynchronous shape as AsyncStorage, plus the JSON and migration helpers you would write on top of the real thing.

Key-value storage

All three tools work like a very small database: you save a value under a key, and read it back later by the same key. There are no tables and no queries. That simplicity is the point: it is perfect for settings and small caches, and wrong for large lists of records (use SQLite for those).

Three tools, three jobs

AsyncStorage General purpose, async, strings only.
MMKV Very fast and synchronous.
SecureStore Encrypted keys and tokens.

Match the tool to how sensitive and how large the data is.

1 / 2

AsyncStorage

@react-native-async-storage/async-storage is the long-standing default. Every call returns a promise, and values are strings.

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

await AsyncStorage.setItem('username', 'ada');
const name = await AsyncStorage.getItem('username'); // 'ada', or null if missing
await AsyncStorage.removeItem('username');

// Several keys at once
await AsyncStorage.multiSet([['a', '1'], ['b', '2']]);
const pairs = await AsyncStorage.multiGet(['a', 'b']); // [['a','1'], ['b','2']]

Remember three things about it. It is not encrypted: anyone with access to the device's files (a rooted phone, a backup) can read it. It is asynchronous, so you cannot read it during the first render; screens usually load values in an effect or wait behind the splash screen. And it has size limits: on Android the whole database defaults to about 6 MB, so do not use it as a place to dump API responses.

Objects need JSON

Because only strings are stored, you convert objects with JSON.stringify and back with JSON.parse:

JSX
await AsyncStorage.setItem('settings', JSON.stringify({ theme: 'dark', fontScale: 1.2 }));

const raw = await AsyncStorage.getItem('settings');
const settings = raw ? JSON.parse(raw) : { theme: 'light', fontScale: 1 };

JSON has limits worth knowing. Date objects become strings. undefined, functions and Map/Set are lost or changed. And JSON.parse throws on corrupt data. So wrap reading and writing in small helpers, once, and use them everywhere.

A storage adapter with JSON helpers

Try "Save with setJSON", then "Save a Date": the value that comes back is a string, not a Date. Parse it back yourself (new Date(value)) when you read it.

Working with several keys at once

AsyncStorage can read, write and remove many keys in one call, which is faster than looping with await and keeps related keys consistent:

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

// Write several keys at once: an array of [key, value] pairs
await AsyncStorage.multiSet([
  ['user:name', 'Ada'],
  ['user:theme', 'dark'],
  ['user:lang', 'en'],
]);

// Read several keys: returns [[key, value], ...], with null for missing keys
const pairs = await AsyncStorage.multiGet(['user:name', 'user:theme', 'user:missing']);
const settings = Object.fromEntries(pairs);   // { 'user:name': 'Ada', 'user:theme': 'dark', 'user:missing': null }

// Merge a partial update into an existing JSON value
await AsyncStorage.mergeItem('prefs', JSON.stringify({ fontScale: 1.2 }));

// Remove several keys (for example on sign-out)
await AsyncStorage.multiRemove(['user:name', 'user:theme', 'user:lang']);

// List every key, then remove just yours
const keys = await AsyncStorage.getAllKeys();
await AsyncStorage.multiRemove(keys.filter((k) => k.startsWith('user:')));

Prefix keys with a namespace (user:, cache:) so a group can be found and cleared without touching the rest. Use AsyncStorage.clear() only when you really mean to erase everything the app stored with it, including other libraries' data. For "store and retrieve one small value", setItem and getItem are enough; the multi methods pay off when several values belong together, such as a whole sign-out.

MMKV

MMKV (from react-native-mmkv) is a storage engine that talks to native code directly, so reads and writes are synchronous and very fast. That makes it a pleasant fit for things you need on the very first render, such as the theme, and a good backing store for Zustand's persist middleware.

JSX
import { MMKV } from 'react-native-mmkv';

export const storage = new MMKV();

storage.set('username', 'ada');
storage.set('launchCount', 3);
storage.set('notificationsOn', true);

const name = storage.getString('username');
const count = storage.getNumber('launchCount');
storage.delete('username');

It stores strings, numbers and booleans natively (objects still need JSON). Two cautions: it needs native code, so it works in a development build but not in Expo Go, and the way you create the instance has changed between major versions of the library, so follow the documentation of the version you install.

SecureStore

Secrets such as access tokens, refresh tokens and API credentials for the signed-in user need encryption at rest. expo-secure-store stores values in the platform's secure facilities: the Keychain on iOS and Keystore-backed encrypted storage on Android.

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

await SecureStore.setItemAsync('refreshToken', token, {
  keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK,
});
const saved = await SecureStore.getItemAsync('refreshToken'); // string or null
await SecureStore.deleteItemAsync('refreshToken');

It is meant for small values: keys may only contain letters, digits, ., - and _, and large values (around 2 KB and more) are discouraged. An option requireAuthentication: true makes reads wait for the user's fingerprint or face. Keychain items on iOS can even survive uninstalling and reinstalling the app, so do not assume a fresh install means an empty Keychain; delete the token at sign-out and consider clearing stale data on first launch.

What belongs where

Data Where Why
Theme, language, onboarding done AsyncStorage or MMKV Not sensitive, small
Draft message, last search AsyncStorage or MMKV Convenience only
Access token, refresh token SecureStore Gives access to the account
Password Do not store it Keep only a token
Hundreds of records SQLite Needs queries and size
Cached API data A query cache Needs stale and refetch rules

A good test is: "if someone read this file from a stolen, backed-up phone, would it matter?" If yes, it goes in SecureStore, or better, you do not store it at all. Mobile security is covered in depth in Mobile App Security.

Migrations: when the shape changes

Your app will be updated, and the format of what you saved will change. Version 1 stored { dark: true }; version 2 wants { theme: 'dark' }. A user who skips an update arrives with old data, and your new code must still read it. The fix is cheap if you plan it early: store a schema version next to your data and, at startup, run the missing steps in order.

JSX
const LATEST = 3;

async function migrate() {
  let version = Number(await AsyncStorage.getItem('schemaVersion')) || 0;
  while (version < LATEST) {
    version += 1;
    await steps[version]();                                   // upgrade the data
    await AsyncStorage.setItem('schemaVersion', String(version)); // record progress
  }
}

Saving the version after each step means a crash half-way resumes where it stopped instead of starting over. Pick one of the "install" buttons below to simulate an older app, then launch the latest version.

Running storage migrations in order

Notice that "Fresh install" runs all three steps and ends with the same result as upgrading from v1 or v2: one code path serves new and old users alike.

Practical habits

  • Wrap storage in your own module. Components call settings.get() and never the library directly, so swapping AsyncStorage for MMKV later touches one file.
  • Namespace your keys (app.settings.v1), and keep a single place that lists them.
  • Validate what you read. Stored data can be missing, old or corrupt; always have a fallback.
  • Clear on sign-out. Remove user data and tokens when the user logs out.
  • Do not store large blobs. Photos and downloads belong in the file system (expo-file-system), with only the path stored.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must you call JSON.stringify before saving an object with AsyncStorage?

    AsyncStorage values are strings. Convert objects to JSON when saving and parse them when reading, with a fallback for missing or corrupt data.
  2. 2. Where should a refresh token be stored?

    A token gives access to the account, so it needs encryption at rest. AsyncStorage is not encrypted and the bundle can be read by anyone.
  3. 3. What is the main advantage of MMKV over AsyncStorage?

    MMKV talks to native code directly, so you can read values on the first render. It needs a development build and is not a replacement for a database.
  4. 4. Why save the schema version after each migration step?

    Recording progress per step makes migrations safe to interrupt and keeps every user, new or old, on the same upgrade path.

Summary

  • Key-value storage keeps small pieces of data under string keys; it is for settings and small caches, not for large record lists.
  • AsyncStorage is async, string-only, unencrypted and limited in size; use JSON helpers with fallbacks and watch for types JSON changes, such as dates.
  • MMKV is synchronous and fast but needs a development build; SecureStore encrypts small secrets using Keychain and Keystore.
  • Match the tool to the data: secrets in SecureStore, preferences in AsyncStorage or MMKV, records in SQLite, API data in a query cache.
  • Store a schema version and run migration steps in order, saving the version after each step.
  • Wrap storage in your own module and clear user data at sign-out.
  • On this site the real libraries are read-only; the adapter and migration demos are stand-ins.

Next, move from key-value pairs to real tables with Local Databases with SQLite.