React Native
AsyncStorage
Save notes with AsyncStorage.
What is AsyncStorage?
AsyncStorage is the module that provides persistent storage in React Native. It keeps data even when the app closes; it is a key-value store. You save with AsyncStorage.setItem("notes", value) and read with AsyncStorage.getItem("notes").
All operations are async; so you use await. The value can only be a string; so you turn objects and arrays into strings with JSON.stringify before saving and back with JSON.parse when reading. AsyncStorage is ideal for small data like notes; for larger data alternatives like SQLite are preferred.
Exercise Save with AsyncStorage
Add an async function named saveNotes to the NotesApp component. Save the notes with AsyncStorage.setItem("notes", JSON.stringify(notes)). The function uses await.
Show example solution
import { useState } from "react";
import { Text, TextInput } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
function NotesApp() {
const [notes, setNotes] = useState([{ id: "1", title: "Shopping", body: "Milk, bread" }]);
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
async function saveNotes() {
await AsyncStorage.setItem("notes", JSON.stringify(notes));
}
return <Text>Notes</Text>;
}
Reading from AsyncStorage
After saving you need to load the notes back when the app opens. You read the saved string with AsyncStorage.getItem("notes"); this operation is async, so you use await. The returned string is turned into an object with JSON.parse.
You put the read inside useEffect; so when the component first appears on screen (mount) the notes load. With an empty array [] as the dependency array, this effect runs only once. If no record exists getItem returns null; in that case you use an empty array. This way the app loads saved notes on every opening.
Test yourself
-
Read from AsyncStorage
const raw = await AsyncStorage.____("notes");
Show answer
const raw = await AsyncStorage.getItem("notes");
-
When should AsyncStorage be loaded?
useEffect(() => {
/* yükleme */
}, []);
- Her render'da
- useEffect ile mount'ta
- Only when the button is pressed
- Never
Show answer
useEffect ile mount'ta — It is loaded on mount with useEffect.
-
Match each piece to its role
- AsyncStorage.setItem
- Saves
- AsyncStorage.getItem
- Reads
- JSON.stringify
- Object to string
- JSON.parse
- String to object
Next lesson: Putting it together