← Back to Chapters

AsyncStorage

? AsyncStorage

✨ Quick Overview

AsyncStorage is a simple, unencrypted, asynchronous, persistent key-value storage system for React Native. It is commonly used to store small amounts of data such as user preferences, tokens, or app settings.

? Key Concepts

  • Asynchronous key-value storage
  • Data persists across app restarts
  • Works like localStorage but async
  • Uses Promises / async-await

? Syntax / Theory

AsyncStorage provides methods to set, get, remove, and clear data. Values are always stored as strings, so objects must be serialized using JSON.

? Code Example – Save Data

? View Code Example
// Import AsyncStorage from the community package
import AsyncStorage from '@react-native-async-storage/async-storage';

const saveData = async () => {
  try {
    // Store a string value using a key
    await AsyncStorage.setItem('username', 'Meghraj');
  } catch (e) {
    // Handle saving error
    console.log(e);
  }
};

? Code Example – Read Data

? View Code Example
// Function to read stored data
const readData = async () => {
  try {
    const value = await AsyncStorage.getItem('username');
    if (value !== null) {
      // Value successfully retrieved
      console.log(value);
    }
  } catch (e) {
    // Handle reading error
    console.log(e);
  }
};

? Live Output / Explanation

Expected Behavior

The stored value is retrieved asynchronously and printed in the console. If the app restarts, the value remains available until removed.

? Interactive Example (Simulation)

Since this is a web page, we will use the browser's storage to simulate how AsyncStorage works on a phone. The logic is identical: Key-Value pairs that persist.

? Simulated Device Storage:

{}
Ready...
? View React Native Button Code
// Example button usage with AsyncStorage
<Button title="Save Name" onPress={saveData} />
<Button title="Read Name" onPress={readData} />

? Use Cases

  • Storing authentication tokens
  • Saving user preferences (theme, language)
  • Caching small API responses
  • Remembering login state

✅ Tips & Best Practices

  • Always use async/await for cleaner code
  • Serialize objects using JSON.stringify
  • Do not store sensitive data
  • Use meaningful and unique keys

? Try It Yourself

  • Store and retrieve a counter value
  • Save a theme preference (dark/light)
  • Clear all stored data on logout