AsyncStorage is a simple, unencrypted, asynchronous, persistent key-value storage system for React Native. It is commonly used to store small amounts of data such as user preferences, tokens, or app settings.
AsyncStorage provides methods to set, get, remove, and clear data. Values are always stored as strings, so objects must be serialized using JSON.
// Import AsyncStorage from the community package
import AsyncStorage from '@react-native-async-storage/async-storage';
const saveData = async () => {
try {
// Store a string value using a key
await AsyncStorage.setItem('username', 'Meghraj');
} catch (e) {
// Handle saving error
console.log(e);
}
};
// Function to read stored data
const readData = async () => {
try {
const value = await AsyncStorage.getItem('username');
if (value !== null) {
// Value successfully retrieved
console.log(value);
}
} catch (e) {
// Handle reading error
console.log(e);
}
};
The stored value is retrieved asynchronously and printed in the console. If the app restarts, the value remains available until removed.
Since this is a web page, we will use the browser's storage to simulate how AsyncStorage works on a phone. The logic is identical: Key-Value pairs that persist.
? Simulated Device Storage:
// Example button usage with AsyncStorage
<Button title="Save Name" onPress={saveData} />
<Button title="Read Name" onPress={readData} />