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
JSON.stringify() before storing and
JSON.parse() after reading.
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"
Applications often need to remember simple information between sessions.
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.
import AsyncStorage
from "@react-native-async-storage/async-storage";
The imported object provides methods for saving, reading and removing stored values.
AsyncStorage works using keys and values.
Key:
"userName"
Value:
"Rahul"
The key is used later to retrieve the stored value.
The setItem() method is used to store data.
await AsyncStorage.setItem(
"userName",
"Rahul"
);
The value is stored under the key userName.
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.
Calling setItem() again with the same key replaces the
previous value.
await AsyncStorage.setItem(
"userName",
"Amit"
);
The value associated with userName is now
Amit.
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.
The clear() method removes all AsyncStorage data available
to the application.
await AsyncStorage.clear();
clear() carefully because it can remove multiple stored
values, not just one specific key.
AsyncStorage operations are asynchronous, so they return Promises.
await AsyncStorage.setItem(
"theme",
"dark"
);
The await keyword waits for the storage operation to
complete.
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);
}
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"
)
);
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";
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)
);
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);
Arrays can also be stored by converting them into JSON.
const courses = [
"HTML",
"CSS",
"React Native"
];
await AsyncStorage.setItem(
"courses",
JSON.stringify(courses)
);
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.
AsyncStorage can be read when a component starts.
useEffect(() => {
loadUser();
}, []);
The loadUser() function can read the stored value and update
component 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.
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.
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.
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.
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.
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.
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.
| 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 |
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.
npm install @react-native-async-storage/async-storage.setItem() to store values.getItem() to read values.removeItem() to remove a specific value.clear() carefully because it removes all stored application data.JSON.stringify() to store objects and arrays.JSON.parse() to read objects and arrays.Question: Which AsyncStorage method is used to store a value?