What is @react-native-async-storage/async-storage?
@react-native-async-storage/async-storage is a simple, unencrypted, asynchronous, persistent, key-value storage system for React Native applications. It is designed to store small amounts of data, such as user preferences, settings, and other state information.
What are @react-native-async-storage/async-storage's main functionalities?
Store Data
This feature allows you to store data in the form of key-value pairs. The code sample demonstrates how to store a string value with a specific key.
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (e) {
// saving error
}
};
storeData('username', 'JohnDoe');
Retrieve Data
This feature allows you to retrieve data stored in AsyncStorage using a key. The code sample demonstrates how to get a stored value and handle it.
import AsyncStorage from '@react-native-async-storage/async-storage';
const getData = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if(value !== null) {
// value previously stored
return value;
}
} catch(e) {
// error reading value
}
};
getData('username').then(value => console.log(value));
Remove Data
This feature allows you to remove data from AsyncStorage using a key. The code sample demonstrates how to delete a stored value.
import AsyncStorage from '@react-native-async-storage/async-storage';
const removeData = async (key) => {
try {
await AsyncStorage.removeItem(key);
} catch(e) {
// remove error
}
};
removeData('username');
Clear All Data
This feature allows you to clear all data stored in AsyncStorage. The code sample demonstrates how to clear all stored values.
import AsyncStorage from '@react-native-async-storage/async-storage';
const clearAll = async () => {
try {
await AsyncStorage.clear();
} catch(e) {
// clear error
}
};
clearAll();
Other packages similar to @react-native-async-storage/async-storage
react-native-mmkv
react-native-mmkv is a fast, small, and easy-to-use key-value storage library for React Native. It is based on Facebook's MMKV storage library and offers better performance compared to AsyncStorage. However, it may not be as widely supported or documented as AsyncStorage.
react-native-sensitive-info
react-native-sensitive-info is a library for storing sensitive information securely in React Native applications. It uses the device's secure storage mechanisms, such as Keychain on iOS and Keystore on Android, to store data securely. This makes it a better choice for storing sensitive data compared to AsyncStorage, which is not encrypted.
redux-persist
redux-persist is a library that allows you to persist and rehydrate a Redux store. It can be used to store the entire Redux state or specific parts of it in various storage backends, including AsyncStorage. It is useful for applications that use Redux for state management and need to persist state across sessions.