AsyncStorage
AsyncStorage
is a data storage system in React Native that is unencrypted, asynchronous, and allows users to persist data offline in React Native apps.
Because AsyncStorage
is unencrypted, the stored data is not converted into code or encrypted to prevent unauthorized access, meaning anyone with your device can easily get to the data.
However, since it is unencrypted, getting or retrieving data from the AsyncStorage
is easier and does not involve any further decryption.
AsyncStorage
is also asynchronous, meaning that its methods run concurrently with the rest of your code, and it’s persistent, meaning that the stored data will always be available globally even if you log out or restart the application.
This allows you to use and access the data from any React Native component and increases the app’s performance and experience since storing and retrieving data from the AsyncStorage
does not affect the other codes from running.
AsyncStorage
just like the localStorage
in the web, persists data using key-value pairs just like localStorage
. If you have used localStorage
and sessionStorage
before, then AsyncStorage
will be familiar and easy to use.
In this article, we’ll cover how AsyncStorage
works, the importance of AsyncStorage
, use cases, and how to use the AsyncStorage
methods to interact with a data storage system, including:
AsyncStorage
worksAsyncStorage
accepts and stores only string data, so we must always serialize the data before storing it if it is not a string. This means that we must first convert it to string data before storing it; here, the key and the value are both strings.
To convert the object we want to save to a string, we use JSON.stringify()
. In situations where we get data back from the storage, we use the JSON.parse()
to convert back to object:
// storing data const storeUser = async (value) => { try { await AsynStorage.setItem("user", JSON.stringify(value)); } catch (error) { console.log(error); } }; // getting data const getUser = async () => { try { const userData = JSON.parse(await AsynStorage.getItem("user")) } catch (error) { console.log(error); } };
There are many scenarios where you can use the AsyncStorage
, like storing data for themes or storing offline data.
However, it is not advisable to store sensitive information in AsyncStorage
since it is not safe for sensitive information. This is because anyone with access to your phone can read the data stored in your phone’s document file system.
AsyncStorage
Before using the AsyncStorage
, we must first install the AsyncStorage
package. To install the package, open up your terminal and run any of the commands below:
#using npm npm install @react-native-async-storage/async-storage #using yarn yarn add @react-native-async-storage/async-storage
After that, you can import it inside any of the React Native’s components that you want to use. Simply import it from the module and then call any of the methods:
// React Native component import AsyncStorage from '@react-native-async-storage/async-storage';
AsyncStorage
methodsAsyncStorage
methods have several ways that work or interact with the React Native async
data storage system. They offer developers ways to perform and execute actions within the storage system.
We can perform three main actions with AsyncStorage
: Set
, Get
, and Delete
:
Set
sets or stores data in the async
storage using the key-value pairsGet
gets data values from the async
storage using the keyDelete
deletes a particular piece of data or multiple pieces of data using the keyWithout these methods, we cannot perform these actions with AsycnStorage
. These methods include:
setItem()
getItem()
mergeItem()
removeItem()
multiGet()
clear()
Because AsyncStorage
uses a key and a value to store data, the key is the name we want to store the data in while the value is the data that we store.
setItem()
methodThe setItem
method saves data to the AsyncStorage
and allows a key and a value. Here, the key is a string that the data or value is assigned to:
// React Native component const value = { name: "Chimezie", job: "Software Developer" }; const storeUser = async () => { try { await AsyncStorage.setItem("user", JSON.stringify(value)); } catch (error) { console.log(error); } };
The value
object is the data we want to save. To save it, we must first serialize it because AsyncStorage
only stores strings, and we can use the JSON.stringify()
to serialize it.
getItem()
methodThe getItem()
method allows us to get data back from AsyncStorage
by using the key the data was saved as.
For example, assuming we saved the data above using setItem
, we receive the data back using the key "user"
:
// React Native component const getUser = async () => { try { const savedUser = await AsyncStorage.getItem("user"); const currentUser = JSON.parse(savedUser); console.log(currentUser); } catch (error) { console.log(error); } };
mergeItem()
methodThe mergeItem
method modifies or merges an existing value under a key by replacing the value with a new value:
// React Native component const value = { name: "Innocent" }; const mergeUser = async () => { try { await AsyncStorage.mergeItem("user", JSON.parse(value)); } catch (error) { console.log(error); } };
In the above scenario, value
in AsyncStorage
will be replaced with this new value "Innocent"
.
removeItem()
methodThe removeItem()
method removes data from AsyncStorage
by using the key to delete the stored data:
// React Native component const removeUser = async () => { try { await AsyncStorage.removeItem("user"); } catch (error) { console.log(error); } };
clear()
methodThe clear
method deletes or removes all the data from AsyncStorage
. It does not need a key because it deletes all the stored data:
// React Native component const removeData = async () => { try { const savedUser = await AsyncStorage.clear(); } catch (error) { console.log(error); } };
multiGet()
methodThe multiGet
method, as the name implies, gets multiple pieces of data from AsyncStorage
and returns an array of key-value pairs.
If we have multiple pieces of data in the storage system, like storing city
and user
data, we can get both by using the multiGet
method:
// React Native component const getMultipleData = async () => { try { const savedData = await AsyncStorage.multiGet(["city", "user"]); console.log(savedData); } catch (error) { console.log(error); } };
From here, it returns an array of the two pieces of data: city
and user
with the keys and values.
multiSet()
methodThis method stores multiple key-value pairs at once. The multiSet
method accepts and stores the data in arrays.
For example, if we want to store multiple unrelated pieces of data like places
and food
, we can achieve this using the multiSet
method:
// React Native component const places = { name: "Abuja", country: "Nigeria" }; const food = { name: "Spaghetti Pasta" }; const firstData = ["places", JSON.stringify(places)]; const secondData = ["food", JSON.stringify(food)]; const storeMultipleData = async () => { try { await AsyncStorage.multiSet([firstData, secondData]); } catch (error) { console.log(error); } };
places
and food
are the two objects we want to store. So, we assign them to different arrays with key-value pairs. Also, notice that we stringified the objects before parsing them to the multiSet
array. This is because AsyncStorage
does not accept anything except strings.
multiMerge()
methodThe multiMerge
method merges multiple pieces of existing data with new data and does so in a batch:
// React Native component const places = { name: "Mumbai", country: "India" }; const food = { name: "Rice" }; const firstData = ["places", JSON.stringify(places)]; const secondData = ["food", JSON.stringify(food)]; const mergeMultiData = async () => { try { await AsyncStorage.multiMerge([firstData, secondData]); } catch (error) { console.log(error); } };
multiRemove()
methodThis method removes or deletes multiple key-value pairs by deleting the data in a batch using an array of keys.
Let’s delete the two arrays we created above, that is, the places
and food
data:
// React Native component const multiRemoveData = async () => { try { await AsyncStorage.multiRemove(["places", "food"]); } catch (error) { console.log(error); } };
As stated above, it is not advisable to use the AsyncStorage
to store sensitive data like API key, tokens, user details, and so on because it can be accessed easily. However, a good and major use case would be to store themes using AsyncStorage
.
Dark themes are very common in applications these days and are widely appreciated by users. When a user selects dark mode as the preferred theme, a better way to persist the data so the user doesn’t need to continuously select it on login would be to store it in AsyncStorage
.
AsyncStorage
stores and persists the data so that even after the user logs out and logs in later, the persisted data (in this case, the dark theme) will still be available.
As a developer, all you need to do is check if the data exists in the data storage system; if it does (meaning the dark theme exists), the app theme automatically becomes dark, and if not, the app will open with the default light theme.
We have now seen the different methods that AsyncStorage
offers us, including how to use the different AsyncStorage
methods and a use case where we can apply them. Hopefully, this article has helped simplified React Native’s AsyncStorage
. Thank you for reading!
LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.
LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.
Start proactively monitoring your React Native apps — try LogRocket for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
One Reply to "A guide to React Native’s <code>AsyncStorage</code>"
Can Async Storage persist and retrieve user stored values (e.g, a league table values) across devices? Like a user creates a table in an app after logging in (firebase handles auth), then logs out and uses another device to log into same app, will his created table still exist?