Introduction
In React Native applications, AsyncStorage is a data storage system that is asynchronous and unencrypted. Asynchronous Storage is unencrypted, which means that anyone with access to your device can easily access the data since it's not turned into code nor encrypted.
Data can be retrieved from the AsyncStorage much easier because it is unencrypted and no further decryption is required. Also, AsyncStorage is asynchronous, which means that its methods run concurrently with your code, and persistent, meaning it is always accessible even when the application is restarted or logged out.
By using AsyncStorage, you can access and use data from any React Native component and increase the app's performance and experience as storing and retrieving data from the AsyncStorage does not interfere with other code executions.
In the same way as localStorage in the web, AsyncStorage persists data via key-value pairs. It will be easy for you to use AsyncStorage if you have used localStorage and sessionStorage before.
Applications with dark themes are very popular these days, and users love them. It would be better to store the data in AsyncStorage when a user selects dark mode as their preferred theme so they do not have to continuously select it. Even after logging out and logging in later, AsyncStorage retains the persisted data (in this case, the dark theme) until you delete it.
The only thing a developer needs to check is if the dark theme exists in the data storage system; if so, the app theme will automatically become dark, and if not, the light theme will be used.
Click on the following link to read further: Hooks in React JS
How AsyncStorage works
SyncStorage only accepts and stores string data, so if the data is not a string, we must serialize it before storing it. The key and value here are both strings, so we must convert them first to string data before storing them.
We use JSON.stringify() to convert the object to a string. We use JSON.parse() to convert data back to objects when we receive it from storage:
// 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);
}
};
Data for themes or offline data can be stored using AsyncStorage in many scenarios. Nevertheless, sensitive information should not be stored in AsyncStorage because it is not secure.