AsyncStorage로 읽고 쓰기
@react-native-async-storage/async-storage를 설치하고 setItem과 getItem으로 문자열 값을 저장하고 가져오며 반환된 Promise를 올바르게 처리합니다.
AsyncStorage로 읽고 쓰기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is AsyncStorage?
AsyncStorage is React Native's persistent key-value storage system. It stores data as strings on the device's local file system, making it available even after the app is closed and reopened. It works on both iOS and Android and supports any string-serializable value. All operations are asynchronous and return Promises, so you must await them or chain .then().
Installing the Package
The community AsyncStorage package must be installed separately in modern React Native and Expo projects. It is no longer bundled with React Native core. Use npx expo install (instead of plain npm) so Expo picks the compatible version for your SDK.
npx expo install @react-native-async-storage/async-storageWriting Data with setItem
AsyncStorage.setItem(key, value) stores a string value at the given key. Both the key and the value must be strings. If the key already exists, the value is overwritten. Always await the call inside a try-catch block to handle potential errors, such as storage being full on the device.
import AsyncStorage from '@react-native-async-storage/async-storage';
async function saveUsername(username: string) {
try {
await AsyncStorage.setItem('username', username);
console.log('Saved successfully');
} catch (error) {
console.error('Failed to save username:', error);
}
}Reading Data with getItem
AsyncStorage.getItem(key) retrieves the string value for the given key. It returns null if the key does not exist — handle this case to avoid runtime errors. A common pattern is to check for null and fall back to a default value when the app launches for the first time.
async function loadUsername(): Promise<string> {
try {
const value = await AsyncStorage.getItem('username');
if (value !== null) {
return value;
}
return 'Guest'; // default when key does not exist
} catch (error) {
console.error('Failed to load username:', error);
return 'Guest';
}
}Removing Data with removeItem
AsyncStorage.removeItem(key) deletes the entry for the given key from storage. After removal, calling getItem for that key returns null. Use this when the user logs out, resets preferences, or deletes their account — any time you need to erase specific stored data without clearing everything.
async function clearSession() {
try {
await AsyncStorage.removeItem('authToken');
await AsyncStorage.removeItem('userId');
console.log('Session cleared');
} catch (error) {
console.error('Failed to clear session:', error);
}
}Loading Data on App Start with useEffect
A typical pattern is to load persisted data into component state when a screen mounts. Use useEffect with an empty dependency array so it runs only once on mount. Set a loading flag while the data loads and clear it when the read completes so the UI shows a spinner instead of blank or stale content.
export default function SettingsScreen() {
const [theme, setTheme] = React.useState('light');
const [loading, setLoading] = React.useState(true);
useEffect(() => {
async function loadTheme() {
const saved = await AsyncStorage.getItem('theme');
if (saved) setTheme(saved);
setLoading(false);
}
loadTheme();
}, []);
if (loading) return <ActivityIndicator />;
return <Text>Current theme: {theme}</Text>;
}Batch Operations with multiSet and multiGet
Reading or writing several keys in a loop is inefficient. Use AsyncStorage.multiSet and AsyncStorage.multiGet to perform batch operations in a single native call. multiSet accepts an array of [key, value] pairs, and multiGet returns an array of the same format with the retrieved values.
// Write multiple keys in one call
await AsyncStorage.multiSet([
['theme', 'dark'],
['language', 'en'],
['fontSize', '16'],
]);
// Read multiple keys in one call
const pairs = await AsyncStorage.multiGet(['theme', 'language', 'fontSize']);
const settings = Object.fromEntries(pairs);
console.log(settings); // { theme: 'dark', language: 'en', fontSize: '16' }Listing All Keys
AsyncStorage.getAllKeys() returns an array of every key currently stored by the app. This is useful for debugging, for building a cache-clearing screen, or for reading all entries without knowing the keys in advance. Combine it with multiGet to load the full storage contents at once.
async function debugStorage() {
const keys = await AsyncStorage.getAllKeys();
console.log('All keys:', keys);
const pairs = await AsyncStorage.multiGet(keys);
pairs.forEach(([key, value]) => {
console.log(key, '->', value);
});
}Clearing All Data with clear
AsyncStorage.clear() deletes all keys stored by the app. Use this with caution — it is a destructive operation with no built-in undo. It is appropriate for a factory reset feature or for wiping all data during development, but never call it without explicit user confirmation in a production app.
async function factoryReset() {
Alert.alert('Reset App', 'This will delete all your data. Are you sure?', [
{ text: 'Cancel', style: 'cancel' },
{
text: 'Reset',
style: 'destructive',
onPress: async () => {
await AsyncStorage.clear();
navigation.reset({ index: 0, routes: [{ name: 'Onboarding' }] });
},
},
]);
}Error Handling Best Practices
AsyncStorage operations can fail when the device is low on storage or when a native bridge error occurs. Always wrap reads and writes in try-catch blocks. For reads, return a sensible default on error. For writes, consider queuing the write to retry later or notifying the user that their setting could not be saved.
async function safeSave(key: string, value: string) {
try {
await AsyncStorage.setItem(key, value);
return true;
} catch (err) {
if (__DEV__) console.error('AsyncStorage write failed:', err);
// Optionally: show a Snackbar or Toast to the user
return false;
}
}AsyncStorage Limits and Alternatives
AsyncStorage is designed for small amounts of data — user preferences, tokens, and simple settings. It is not suitable for large datasets (images, documents, or thousands of records), for which you should consider SQLite (via expo-sqlite). Also note that AsyncStorage data is not encrypted by default, so use Expo SecureStore for sensitive credentials.
Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: setItem and getItem are the core AsyncStorage APIs for writing and reading string values keyed by name, multiSet and multiGet batch multiple operations into a single efficient native call, and null checking is essential because getItem returns null for keys that have never been written. Next up we explore storing and parsing JSON objects in AsyncStorage.
자주 묻는 질문
“AsyncStorage로 읽고 쓰기” 강의는 무료인가요?
네 — “AsyncStorage로 읽고 쓰기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“AsyncStorage로 읽고 쓰기”에서 뭘 배우나요?
@react-native-async-storage/async-storage를 설치하고 setItem과 getItem으로 문자열 값을 저장하고 가져오며 반환된 Promise를 올바르게 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“AsyncStorage로 읽고 쓰기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- AsyncStorage로 읽고 쓰기
- JSON 객체 저장 및 파싱
- 영구 설정 화면 만들기
- 저장소 삭제와 마이그레이션 전략