Lesson 55 of 60 – AsyncStorage in React Native
92%

AsyncStorage in React Native

AsyncStorage is a persistent storage solution commonly used in React Native applications to store small amounts of data locally on the device. It can be useful for information such as application preferences, simple settings, and non-sensitive cached data.

Unlike normal React state, data stored in AsyncStorage can remain available after the application is closed and opened again.

React Native App
       ↓
   AsyncStorage
       ↓
Device Local Storage
       ↓
Application Restarts
       ↓
Data Can Be Read Again
Note: AsyncStorage stores string values. Objects and arrays normally need to be converted using JSON.stringify() before storing and JSON.parse() after reading.

1. What is AsyncStorage?

AsyncStorage is an asynchronous persistent key-value storage system for React Native applications.

It allows an application to save small pieces of data locally and read them later.

Key → Value

"userName" → "Rahul"
"theme"    → "dark"

2. Why Use AsyncStorage?

Applications often need to remember simple information between sessions.

  • User preferences
  • Application settings
  • Simple local flags
  • Cached non-sensitive data
  • Onboarding completion status
  • Last selected option

3. Installing AsyncStorage

AsyncStorage is installed as a separate package.

npm install @react-native-async-storage/async-storage

After installation, import AsyncStorage into the file where you need it.

4. Importing AsyncStorage

import AsyncStorage
from "@react-native-async-storage/async-storage";

The imported object provides methods for saving, reading and removing stored values.

5. AsyncStorage Key-Value Concept

AsyncStorage works using keys and values.

Key:
"userName"

Value:
"Rahul"

The key is used later to retrieve the stored value.

6. Storing a String

The setItem() method is used to store data.

await AsyncStorage.setItem(
    "userName",
    "Rahul"
);

The value is stored under the key userName.

7. Reading a String

The getItem() method reads a stored value.

const userName =
    await AsyncStorage.getItem(
        "userName"
    );

console.log(userName);

If the key does not exist, the returned value can be null.

8. Updating Stored Data

Calling setItem() again with the same key replaces the previous value.

await AsyncStorage.setItem(
    "userName",
    "Amit"
);

The value associated with userName is now Amit.

9. Removing Stored Data

The removeItem() method removes a stored key.

await AsyncStorage.removeItem(
    "userName"
);

After removal, reading the same key will no longer return the previous stored value.

10. Clearing AsyncStorage

The clear() method removes all AsyncStorage data available to the application.

await AsyncStorage.clear();
Warning: Use clear() carefully because it can remove multiple stored values, not just one specific key.

11. AsyncStorage is Asynchronous

AsyncStorage operations are asynchronous, so they return Promises.

await AsyncStorage.setItem(
    "theme",
    "dark"
);

The await keyword waits for the storage operation to complete.

12. Using try...catch

Storage operations can be wrapped in try...catch so that errors can be handled.

try {

    await AsyncStorage.setItem(
        "userName",
        "Rahul"
    );

} catch (error) {

    console.log(error);

}

13. Storing Numbers

AsyncStorage stores strings, so numbers should be converted to strings when necessary.

const age = 21;

await AsyncStorage.setItem(
    "age",
    age.toString()
);

When reading the value, it can be converted back into a number.

const age =
    Number(
        await AsyncStorage.getItem(
            "age"
        )
    );

14. Storing Boolean Values

Boolean values can also be converted to strings.

await AsyncStorage.setItem(
    "isLoggedIn",
    "true"
);

When reading the value:

const value =
    await AsyncStorage.getItem(
        "isLoggedIn"
    );

const isLoggedIn =
    value === "true";

15. Storing Objects with JSON.stringify()

Objects need to be converted into JSON strings before storing them.

const user = {

    id: 101,
    name: "Rahul",
    course: "React Native"

};

await AsyncStorage.setItem(
    "user",
    JSON.stringify(user)
);

16. Reading Objects with JSON.parse()

After reading an object from AsyncStorage, use JSON.parse() to convert the JSON string back into a JavaScript object.

const value =
    await AsyncStorage.getItem(
        "user"
    );

const user =
    value
    ? JSON.parse(value)
    : null;

console.log(user.name);

17. Storing Arrays

Arrays can also be stored by converting them into JSON.

const courses = [
    "HTML",
    "CSS",
    "React Native"
];

await AsyncStorage.setItem(
    "courses",
    JSON.stringify(courses)
);

18. Reading Arrays

const value =
    await AsyncStorage.getItem(
        "courses"
    );

const courses =
    value
    ? JSON.parse(value)
    : [];

console.log(courses);

The fallback empty array helps when the key has not been stored yet.

19. Using AsyncStorage with useEffect

AsyncStorage can be read when a component starts.

useEffect(() => {

    loadUser();

}, []);

The loadUser() function can read the stored value and update component state.

20. Loading Stored Data into State

const [userName, setUserName] =
    useState("");

async function loadUser() {

    const value =
        await AsyncStorage.getItem(
            "userName"
        );

    if (value) {

        setUserName(value);

    }

}

This allows stored data to become part of the current component state.

21. Saving User Preferences

AsyncStorage can be useful for simple user preferences.

await AsyncStorage.setItem(
    "theme",
    "dark"
);

await AsyncStorage.setItem(
    "language",
    "English"
);

These values can be read when the application starts.

22. Remembering Onboarding Status

An application can store a flag indicating that onboarding has already been completed.

await AsyncStorage.setItem(
    "onboardingCompleted",
    "true"
);

The application can check this value on the next launch.

23. Using AsyncStorage for Login State

An application can store a non-sensitive session-related flag or identifier when appropriate.

await AsyncStorage.setItem(
    "userId",
    "101"
);

The application can read this information when it starts and then perform the appropriate authentication/session check.

Important: Do not treat ordinary AsyncStorage as a secure secret store. Sensitive credentials, private keys, and authentication secrets require an appropriate secure storage solution and a sound authentication design.

24. Removing Login-Related Local Data

When a user logs out, application-specific local session information can be removed.

await AsyncStorage.removeItem(
    "userId"
);

Only remove the keys that belong to the application's session flow.

25. Creating Storage Helper Functions

For larger applications, repeated AsyncStorage operations can be placed inside helper functions.

async function saveUser(user) {

    await AsyncStorage.setItem(
        "user",
        JSON.stringify(user)
    );

}

async function getUser() {

    const value =
        await AsyncStorage.getItem(
            "user"
        );

    return value
        ? JSON.parse(value)
        : null;

}

Helper functions make storage code easier to reuse.

26. Common AsyncStorage Mistakes

  • Forgetting to install the AsyncStorage package.
  • Forgetting to import AsyncStorage.
  • Trying to store an object directly without converting it to JSON.
  • Forgetting to use JSON.parse() when reading stored objects.
  • Not handling asynchronous operations correctly.
  • Using clear() when only one item should be removed.
  • Storing sensitive secrets in ordinary AsyncStorage.
  • Using inconsistent storage keys.
  • Ignoring possible storage errors.

27. Complete AsyncStorage Example

import React, {
    useEffect,
    useState
} from "react";

import {
    View,
    Text,
    Button
} from "react-native";

import AsyncStorage
from "@react-native-async-storage/async-storage";

export default function ProfileScreen() {

    const [userName, setUserName] =
        useState("");

    async function saveUser() {

        try {

            await AsyncStorage.setItem(
                "userName",
                "Rahul"
            );

            setUserName("Rahul");

        } catch (error) {

            console.log(error);

        }

    }

    async function loadUser() {

        try {

            const value =
                await AsyncStorage.getItem(
                    "userName"
                );

            if (value) {

                setUserName(value);

            }

        } catch (error) {

            console.log(error);

        }

    }

    async function removeUser() {

        try {

            await AsyncStorage.removeItem(
                "userName"
            );

            setUserName("");

        } catch (error) {

            console.log(error);

        }

    }

    useEffect(() => {

        loadUser();

    }, []);

    return (

        <View>

            <Text>
                User: {userName}
            </Text>

            <Button
                title="Save User"
                onPress={saveUser}
            />

            <Button
                title="Remove User"
                onPress={removeUser}
            />

        </View>

    );

}

This example demonstrates saving, reading and removing a string value with AsyncStorage.

28. AsyncStorage Best Practices

  • Use clear and consistent storage keys.
  • Wrap storage operations in appropriate error handling.
  • Use JSON.stringify() for objects and arrays.
  • Use JSON.parse() when reading stored objects and arrays.
  • Keep storage helper functions organized in larger applications.
  • Store only the data that the application actually needs locally.
  • Avoid using ordinary AsyncStorage for sensitive secrets.
  • Remove application-specific session data when appropriate.
  • Do not use clear() when removing only one specific key.

29. Important AsyncStorage Methods

Method Purpose
setItem() Stores a string value using a key
getItem() Reads a stored value
removeItem() Removes a specific stored key
clear() Removes all application AsyncStorage data
JSON.stringify() Converts objects or arrays into JSON strings
JSON.parse() Converts JSON strings back into JavaScript values

30. Complete AsyncStorage Workflow

Application Starts
        ↓
Check AsyncStorage
        ↓
getItem()
        ↓
Data Found?
      /   \
    Yes    No
     ↓      ↓
Parse/Use  Default
     ↓      ↓
Update React State
        ↓
Display UI

To Save:
JavaScript Value
      ↓
JSON.stringify()
      ↓
setItem()
      ↓
AsyncStorage

To Remove:
removeItem()
      ↓
Stored Data Removed

AsyncStorage is useful when a React Native application needs simple persistent local storage. Understanding setItem(), getItem(), removeItem(), JSON.stringify() and JSON.parse() gives you the foundation for working with local application data.

📌 Key Points

  • AsyncStorage provides persistent local key-value storage.
  • Install it using npm install @react-native-async-storage/async-storage.
  • Use setItem() to store values.
  • Use getItem() to read values.
  • Use removeItem() to remove a specific value.
  • Use clear() carefully because it removes all stored application data.
  • AsyncStorage operations are asynchronous.
  • Use JSON.stringify() to store objects and arrays.
  • Use JSON.parse() to read objects and arrays.
  • AsyncStorage can store preferences and other non-sensitive local data.
  • Do not use ordinary AsyncStorage as a secure store for sensitive secrets.
  • Use error handling around important storage operations.

🧠 Quick Quiz

Question: Which AsyncStorage method is used to store a value?