Updated Answer at February 2022
React native, officially deprecated the usage of its built-in AsyncStorage
. The latest solution is to install the community package of it.
# Install via NPM
npm install --save @react-native-async-storage/async-storage
# ...or install via YARN
yarn add @react-native-async-storage/async-storage
# ...or install via EXPO
expo install @react-native-async-storage/async-storage
And the implementation is like this
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeKey = '@storage_Key'
const storeData = async (value) => {
try {
await AsyncStorage.setItem(storeKey, value)
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem(storeKey)
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
Old Answer
There are so many options out there, but the most common you can use is the React Native built-in AsyncStorage
.
Sample Code
import { AsyncStorage } from "react-native";
const storeKey = 'myPreference';
storeData = async () => {
try {
await AsyncStorage.setItem(storeKey, 'I like to save it.');
} catch (error) {
// Error saving data
}
}
retrieveData = async () => {
try {
const value = await AsyncStorage.getItem(storeKey);
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
read more at https://facebook.github.io/react-native/docs/asyncstorage.html
Or you could reconsider 3rd party library like:
https://github.com/kevinresol/react-native-default-preference
https://github.com/mCodex/react-native-sensitive-info
AsyncStorage
on recent version of React Native, when remote debugging turned on (android), it will make the app hang. Read this issue github.com/facebook/react-native/issues/15476 – Hemline