Saving Data Locally in React Native
Your goal: Add a book or change its read status, wait for saving to finish, and find that information again after restarting the app.
Before you begin: Complete Forms and User Input. This is Beginner Guide 11, continuing the same Expo Router app and shared BooksProvider. All application files below belong in your separate learning project, not this statically generated publication.
By the end, you will be able to:
- Distinguish React state, local persistence, remote data, and caching.
- Read, write, and remove strings with AsyncStorage and serialize objects as JSON.
- Restore validated user data before allowing edits.
- Save changes in order, report failures, and retry without discarding progress.
- Preserve local books and stable reading-status IDs across remote refreshes and restarts.
State lasts for a session; storage lasts between sessions
useState remembers values across renders while its component remains mounted. A full restart creates a new JavaScript process and new initial state. A provider above the stack survives screen navigation, but it cannot keep that process alive.
| React state | Persistent local storage |
|---|---|
| Lives in the running app’s memory. | Lives in the app’s storage on this device. |
| A setter requests a new render. | A storage write does not update the screen by itself. |
| Easy to read during rendering. | Must be read asynchronously in this lesson. |
| Resets when the owner is recreated. | Normally survives closing and reopening the app. |
We need both: React state drives the interface; a saved copy lets us reconstruct it next time. Restoration, also called hydration, means reading that copy back into state.
Local data here belongs to the reader: their manually entered titles, authors, notes, and reading decisions. Remote data comes from Open Library and is fetched again. Persistence retains information we cannot reconstruct from that API. Caching keeps a reusable copy of data we could fetch again, often with an expiry or refresh policy. Both may use device storage, but this lesson persists user choices; it does not implement an offline API cache.
Local storage does not automatically add cloud backup, an account, or cross-device synchronization. Another phone will not receive these entries.
Choose storage for the data
| Option | Appropriate use |
|---|---|
| AsyncStorage | Small, non-sensitive key/value data. Asynchronous and unencrypted; our choice here. |
| Expo SQLite | Structured collections needing SQL queries, relationships, or transactions. |
| Expo SecureStore | Small sensitive values using platform-protected storage; not a book database. |
| MMKV | Synchronous key/value access through a native library, with additional native setup. Useful when those characteristics are needed. |
Keep private credentials, passwords, tokens, and sensitive notes out of this AsyncStorage example. JSON encoding is not encryption. We need neither a database schema nor another state-management library for this small list.
Pin one compatible API
This guide targets @react-native-async-storage/async-storage 2.2.0, the version recommended by Expo’s AsyncStorage reference when checked on October 29, 2026. In the Expo learning app, run:
npx expo install @react-native-async-storage/async-storage@2.2.0
npm ls @react-native-async-storage/async-storage
The second command should report 2.2.0. Keep the learning app’s lockfile. Use an Expo SDK whose documented AsyncStorage version is 2.2.0; if Expo reports a compatibility mismatch, resolve the SDK/package pairing before following this sample. Expo Go includes its SDK-compatible native module; a custom development build needs rebuilding after adding a native dependency. Do not install this package in the Docusaurus website.
Version 2 uses import AsyncStorage from '@react-native-async-storage/async-storage' and getItem, setItem, and removeItem. See the version 2 usage guide and API reference.
Upstream v3 also exists. Its instance API uses createAsyncStorage(), and its default export retains the legacy storage backend. That is a separate version choice, described in the official v3 migration guide. We deliberately stay on Expo’s recommended 2.2.0 here; do not copy a v3 factory import into these files.
Try small storage operations
Study these functions before the complete app. If experimenting, put them in a temporary file outside src/app and call one from a temporary button handler. They use a disposable key unrelated to the Reading List. Do not call them during rendering.
import AsyncStorage from '@react-native-async-storage/async-storage';
const DEMO_KEY = '@reading-list/demo-label';
export async function writeLabel() {
try {
await AsyncStorage.setItem(DEMO_KEY, 'Weekend reading');
console.log('Label saved.');
} catch {
console.warn('Could not save the label.');
}
}
export async function readLabel() {
try {
const value = await AsyncStorage.getItem(DEMO_KEY);
console.log(value === null ? 'No label saved yet.' : value);
} catch {
console.warn('Could not read the label.');
}
}
export async function removeLabel() {
try {
await AsyncStorage.removeItem(DEMO_KEY);
console.log('Label removed.');
} catch {
console.warn('Could not remove the label.');
}
}
Call writeLabel, then readLabel: expect “Weekend reading”. After removeLabel, reading returns null. An empty string is an existing value, not a missing key. Use removeItem for the intended key rather than clearing unrelated application storage.
These operations use the same async/await pattern as Networking. Wait for the write to finish before reporting success, and handle a rejected Promise with catch.
AsyncStorage stores strings. Serialization converts data into a format that can be stored: here, JSON.stringify() converts our object to JSON text. JSON.parse() reads that text back into a JavaScript value. Parsing does not validate its shape:
import AsyncStorage from '@react-native-async-storage/async-storage';
export async function tryJson() {
const key = '@reading-list/demo-progress';
try {
await AsyncStorage.setItem(key, JSON.stringify({ isRead: true }));
const raw = await AsyncStorage.getItem(key);
if (raw === null) {
console.log('No saved progress.');
return;
}
const value: unknown = JSON.parse(raw);
if (typeof value !== 'object' || value === null
|| !('isRead' in value) || typeof value.isRead !== 'boolean') {
throw new Error('Unexpected progress structure.');
}
console.log(value.isRead); // true
await AsyncStorage.removeItem(key);
} catch {
console.warn('The storage or JSON operation failed.');
}
}
Missing data is null from getItem and is normal on first launch. Corrupted JSON is text that cannot be parsed, such as an incomplete object. Valid JSON such as [] can still have an invalid structure for our app. A TypeScript assertion cannot repair any of those cases. The integrated helper distinguishes them and never silently replaces unreadable data with an empty list.
Extend the existing shared owner
Hooks introduced shared status and derived progress. Navigation passed IDs through routes. Networking moved live results and readById into BooksProvider. Forms added localBooks, notes, and local-<time>-<counter> IDs. We keep that progression:
| Value | Persist? | Reason |
|---|---|---|
localBooks including title, author, optional notes, and ID | Yes | These entries cannot be fetched from Open Library. |
readById for local and remote IDs | Yes | Reading status is the reader’s choice. |
version: 1 | Yes | Recognize the saved format; reject unsupported versions. |
remoteBooks and raw API responses | No | Fetch current metadata normally. |
| Request state, errors, progress percentage, form drafts | No | Temporary or derived values. |
The saved object groups localBooks and readById so each write contains a complete, consistent snapshot. The screen still derives books by combining local entries first with remote results. loadBooks changes only the remote array.
Remote IDs retain the OL…W form; local IDs retain the local- prefix. New local IDs are checked against restored entries as well as entries from this session. That fixes the previous counter’s restart limitation without adding an ID library. It is a single-device scheme, not a distributed ID generator. Store the ID once; never regenerate it during rendering or restoration.
A status for a remote book stays saved even when that book is absent from the latest search. It applies again if the same ID returns. The visible progress count includes only currently visible books. Remote metadata and arbitrary remote deep links remain unavailable offline unless already loaded during this session.
Follow the persistence lifecycle
Open provider → read key → parse and validate
missing key → empty user data → allow editing
valid data → restored user data → allow editing
read/format failure → show Retry → no edits or writes
Add book / toggle status → update shared state → enqueue complete snapshot
write succeeds → Saved on this device
write fails → retain in-memory changes → Retry saving latest snapshot
The provider starts with saved === null, meaning “not restored yet,” not “empty list.” It gates all three screens until storage has been read successfully. This also prevents a directly opened local Details route from briefly saying “Book not found.” Remote fetching runs independently and retains its existing retry, cancellation, and refresh behavior.
There is no save Effect watching initial empty state. Only user actions and explicit save retries call the writer. Restoring a valid or missing record performs no write. An unreadable record keeps the gate closed and remains untouched; Retry performs another read. Persistent format damage needs a deliberate repair or a user-approved reset outside this example, never an automatic deletion.
Each action immediately updates React state and schedules its snapshot. The helper chains storage operations so write B starts only after write A settles. Reads use the same lane, so a remounted provider waits for pending writes. A failed operation is reported to its caller without permanently blocking the lane. A later full snapshot includes earlier in-memory changes, so retry saves the latest whole list.
A save counter controls only the message: an older completion cannot say “Saved” while a newer snapshot is pending or failed. The provider’s ref keeps consecutive actions based on the newest snapshot before React renders again. No storage call runs inside a state updater. Cleanup ignores obsolete restore results and save notifications.
In development Strict Mode, the extra Effect setup can enqueue another read; each setup has its own cancellation flag, and restoration itself never writes. Pending storage operations are not canceled on unmount: they continue through the module queue while the JavaScript runtime lives. A remount waits behind them, but cannot recover an in-memory snapshot whose write failed.
Run the complete application
Keep the working Expo Router project, safe-area support, and the expo-router/react-navigation header Hook from Forms. What changes in this lesson: Local books and reading decisions can now survive a restart. Add src/storage/readingList.ts to validate and save them, and update BooksProvider.tsx to restore data before showing editable screens. Add Book and Details also get copy that reflects persistence instead of warning that every restart loses local entries.
Reuse the book model, fetch helper, card, root layout, and Home screen from Forms. All eight complete files are included below so you can replace the previous version without assembling fragments. Keep only one route root, src/app.
src/
app/
_layout.tsx
index.tsx
books/
add.tsx
[id].tsx
components/
BookCard.tsx
data/
books.ts
state/
BooksProvider.tsx
storage/
readingList.ts
1. Keep the book model and remote fetch
The Forms model and Open Library request are unchanged. Continue the occasional-use API guidance from Networking; persistence adds no requests.
export type Book = {
id: string;
title: string;
author: string;
firstPublishYear?: number;
notes?: string;
};
type SearchDocument = {
key: string;
title?: string;
author_name?: string[];
first_publish_year?: number;
};
const SEARCH_QUERY = 'react native';
const SEARCH_URL = 'https://openlibrary.org/search.json?q='
+ encodeURIComponent(SEARCH_QUERY)
+ '&limit=10&fields=key,title,author_name,first_publish_year';
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function readDocument(value: unknown): SearchDocument {
if (!isObject(value) || typeof value.key !== 'string'
|| !/^\/works\/OL\d+W$/.test(value.key)) {
throw new Error('The book service returned an invalid book identifier.');
}
return {
key: value.key,
title: typeof value.title === 'string' ? value.title : undefined,
author_name: Array.isArray(value.author_name)
? value.author_name.filter((name: unknown): name is string =>
typeof name === 'string' && name.trim().length > 0)
: undefined,
first_publish_year: typeof value.first_publish_year === 'number'
&& Number.isFinite(value.first_publish_year)
? value.first_publish_year : undefined,
};
}
export async function fetchBooks(signal: AbortSignal): Promise<Book[]> {
const response = await fetch(SEARCH_URL, { signal });
if (!response.ok) {
throw new Error(response.status === 429
? 'The book service is busy. Wait a little before retrying.'
: `Could not load books (HTTP ${response.status}). Please try again.`);
}
const data: unknown = await response.json();
if (!isObject(data) || !Array.isArray(data.docs)) {
throw new Error('The book service returned an unexpected response.');
}
return data.docs.map((value: unknown): Book => {
const doc = readDocument(value);
return {
id: doc.key.replace('/works/', ''),
title: doc.title?.trim() || 'Untitled book',
author: doc.author_name?.map(name => name.trim()).join(', ') || 'Unknown author',
firstPublishYear: doc.first_publish_year,
};
});
}
2. Validate and order storage operations
Validate the version, every local book, unique local IDs, and every boolean status. Only recognized book fields are restored. The queue belongs to this module and key, not to a screen.
import AsyncStorage from '@react-native-async-storage/async-storage';
import type { Book } from '../data/books';
export type SavedReadingList = {
version: 1;
localBooks: Book[];
readById: Record<string, boolean>;
};
const STORAGE_KEY = '@reading-list/user-data';
const localIdPattern = /^local-\d+-\d+$/;
const remoteIdPattern = /^OL\d+W$/;
export function emptyReadingList(): SavedReadingList {
return { version: 1, localBooks: [], readById: {} };
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function readLocalBook(value: unknown): Book {
if (!isObject(value)
|| typeof value.id !== 'string' || !localIdPattern.test(value.id)
|| typeof value.title !== 'string' || !value.title.trim()
|| typeof value.author !== 'string' || !value.author.trim()
|| (value.notes !== undefined && typeof value.notes !== 'string')
|| (value.firstPublishYear !== undefined
&& (typeof value.firstPublishYear !== 'number' || !Number.isFinite(value.firstPublishYear)))) {
throw new Error('A saved local book has an invalid structure.');
}
return {
id: value.id, title: value.title, author: value.author,
notes: value.notes, firstPublishYear: value.firstPublishYear,
};
}
function parseReadingList(raw: string): SavedReadingList {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
throw new Error('Saved reading data is not valid JSON.');
}
if (!isObject(value) || value.version !== 1
|| !Array.isArray(value.localBooks) || !isObject(value.readById)) {
throw new Error('Saved reading data has an unsupported version or invalid structure.');
}
const localBooks = value.localBooks.map(readLocalBook);
const localIds = new Set(localBooks.map(book => book.id));
if (localIds.size !== localBooks.length) {
throw new Error('Saved local books contain duplicate IDs.');
}
const readById: Record<string, boolean> = {};
for (const [id, isRead] of Object.entries(value.readById)) {
if ((!remoteIdPattern.test(id) && !localIds.has(id)) || typeof isRead !== 'boolean') {
throw new Error('Saved reading status has an invalid ID or value.');
}
readById[id] = isRead;
}
return { version: 1, localBooks, readById };
}
// One ordered lane for this key, shared even if the provider remounts.
let storageQueue: Promise<void> = Promise.resolve();
function inStorageOrder<T>(operation: () => Promise<T>): Promise<T> {
const result = storageQueue.then(operation);
// Keep the lane usable after failure; return the original rejection to the caller.
storageQueue = result.then(() => undefined, () => undefined);
return result;
}
export function loadReadingList(): Promise<SavedReadingList> {
return inStorageOrder(async () => {
const raw = await AsyncStorage.getItem(STORAGE_KEY);
return raw === null ? emptyReadingList() : parseReadingList(raw);
});
}
export function saveReadingList(snapshot: SavedReadingList): Promise<void> {
return inStorageOrder(() => AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot)));
}
3. Restore and save in BooksProvider
The provider still owns the combined list and network lifecycle. Its status message is visible above every route, including after Add Book returns home. A failed save preserves the in-memory list and offers Retry saving.
import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { ActivityIndicator, Button, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { loadReadingList, saveReadingList } from '../storage/readingList';
import type { SavedReadingList } from '../storage/readingList';
import { fetchBooks } from '../data/books';
import type { Book } from '../data/books';
type Phase = 'loading' | 'refreshing' | 'idle';
type BooksValue = {
books: Book[];
readById: Record<string, boolean>;
phase: Phase;
hasLoaded: boolean;
error: string | null;
loadBooks: (refresh?: boolean) => Promise<void>;
toggleRead: (id: string) => void;
addBook: (title: string, author: string, notes: string) => void;
};
const BooksContext = createContext<BooksValue | null>(null);
export function BooksProvider({ children }: { children: ReactNode }) {
const [remoteBooks, setRemoteBooks] = useState<Book[]>([]);
const [saved, setSaved] = useState<SavedReadingList | null>(null);
const currentSaved = useRef<SavedReadingList | null>(null);
const books = [...(saved?.localBooks ?? []), ...remoteBooks];
const nextLocalId = useRef(0);
const readById = saved?.readById ?? {};
const [restoreAttempt, setRestoreAttempt] = useState(0);
const [restoreError, setRestoreError] = useState<string | null>(null);
const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const latestSave = useRef(0);
const mounted = useRef(false);
const [phase, setPhase] = useState<Phase>('loading');
const [hasLoaded, setHasLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const activeRequest = useRef<AbortController | null>(null);
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
}, []);
useEffect(() => {
let cancelled = false;
setRestoreError(null);
async function restore() {
try {
const restored = await loadReadingList();
if (cancelled) return;
currentSaved.current = restored;
setSaved(restored);
} catch (cause) {
if (cancelled) return;
setRestoreError(cause instanceof Error ? cause.message : 'Could not read device storage.');
}
}
void restore();
return () => { cancelled = true; };
}, [restoreAttempt]);
function persist(snapshot: SavedReadingList) {
const request = ++latestSave.current;
setSaveState('saving');
void saveReadingList(snapshot).then(
() => {
if (mounted.current && request === latestSave.current) setSaveState('saved');
},
() => {
if (mounted.current && request === latestSave.current) setSaveState('error');
},
);
}
function updateSaved(next: SavedReadingList) {
// Ref supplies the latest snapshot even before React renders another tap.
currentSaved.current = next;
setSaved(next);
persist(next);
}
const loadBooks = useCallback(async (refresh = false) => {
if (activeRequest.current) return;
const controller = new AbortController();
activeRequest.current = controller;
setPhase(refresh ? 'refreshing' : 'loading');
setError(null);
try {
// Space occasional attempts; do not hammer a public service.
await new Promise<void>(resolve => setTimeout(resolve, 1100));
if (controller.signal.aborted) return;
const nextBooks = await fetchBooks(controller.signal);
if (controller.signal.aborted) return;
setRemoteBooks(nextBooks);
setHasLoaded(true);
} catch (cause) {
if (controller.signal.aborted) return;
setError(cause instanceof Error ? cause.message : 'Could not load books. Please try again.');
} finally {
if (!controller.signal.aborted) {
activeRequest.current = null;
setPhase('idle');
}
}
}, []);
useEffect(() => {
void loadBooks();
return () => {
activeRequest.current?.abort();
activeRequest.current = null;
};
}, [loadBooks]);
function addBook(title: string, author: string, notes: string) {
const previous = currentSaved.current;
if (previous === null) return;
// Check restored IDs too: the counter alone resets on restart.
let id: string;
do {
nextLocalId.current += 1;
id = `local-${Date.now()}-${nextLocalId.current}`;
} while (previous.localBooks.some(book => book.id === id));
const newBook: Book = { id, title, author, notes: notes || undefined };
updateSaved({
...previous,
localBooks: [newBook, ...previous.localBooks],
readById: { ...previous.readById, [id]: false },
});
}
function toggleRead(id: string) {
const previous = currentSaved.current;
if (previous === null || !books.some(book => book.id === id)) return;
updateSaved({ ...previous, readById: { ...previous.readById, [id]: !previous.readById[id] } });
}
// No screen can edit or show "not found" before restoration finishes.
if (saved === null) {
return (
<SafeAreaView style={{ flex: 1, padding: 20, gap: 12 }}>
{restoreError === null ? (
<>
<ActivityIndicator accessibilityLabel="Restoring reading list" />
<Text>Restoring your Reading List…</Text>
</>
) : (
<>
<Text accessibilityRole="alert">{restoreError}</Text>
<Text>Saved data has not been changed. Retry reading storage to continue.</Text>
<Button title="Retry restoring data" onPress={() => setRestoreAttempt(value => value + 1)} />
</>
)}
</SafeAreaView>
);
}
return (
<BooksContext.Provider value={{ books, readById, phase, hasLoaded, error, loadBooks, toggleRead, addBook }}>
<View style={{ flex: 1 }}>
<SafeAreaView edges={['top', 'left', 'right']} style={{ paddingHorizontal: 16, paddingBottom: 8 }}>
<Text accessibilityLiveRegion="polite">
{saveState === 'saving' ? 'Saving on this device…'
: saveState === 'saved' ? 'Saved on this device.'
: saveState === 'error' ? 'Changes are in memory only. Saving failed; retry before closing.'
: 'Reading List ready.'}
</Text>
{saveState === 'error' && (
<Button title="Retry saving" onPress={() => {
if (currentSaved.current !== null) persist(currentSaved.current);
}} />
)}
</SafeAreaView>
{children}
</View>
</BooksContext.Provider>
);
}
export function useBooks() {
const value = useContext(BooksContext);
if (value === null) throw new Error('useBooks must be inside BooksProvider.');
return value;
}
4. Keep the three stack routes
Keep the shared owner above all routes. Screens mount after restoration; no navigation call runs during the loading gate.
import { Stack } from 'expo-router';
import { BooksProvider } from '../state/BooksProvider';
export default function RootLayout() {
return (
<BooksProvider>
<Stack>
<Stack.Screen name="index" options={{ title: 'Reading List' }} />
<Stack.Screen name="books/add" options={{ title: 'Add Book' }} />
<Stack.Screen name="books/[id]" options={{ title: 'Book Details' }} />
</Stack>
</BooksProvider>
);
}
5. Keep the reusable card
Opening details and toggling reading progress remain separate actions.
import { Pressable, StyleSheet, Text, View } from 'react-native';
type BookCardProps = {
title: string;
author: string;
isRead: boolean;
onToggleRead: () => void;
onOpenDetails: () => void;
};
export default function BookCard({ title, author, isRead, onToggleRead, onOpenDetails }: BookCardProps) {
const buttonLabel = isRead ? 'Mark as unread' : 'Mark as read';
return (
<View style={styles.card}>
<Pressable
style={({ pressed }) => [styles.bookRow, pressed && styles.detailsPressed]}
onPress={onOpenDetails}
accessibilityRole="button"
accessibilityLabel={'View details: ' + title}
>
<Text
style={styles.bookIcon}
accessible={false}
accessibilityElementsHidden={true}
importantForAccessibility="no"
>
📖
</Text>
<View style={styles.details}>
<Text style={styles.bookTitle}>{title}</Text>
<Text style={styles.author}>{author}</Text>
<Text style={styles.detailsLink}>View details →</Text>
</View>
</Pressable>
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>
<Pressable
style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]}
onPress={onToggleRead}
accessibilityRole="button"
accessibilityLabel={buttonLabel + ': ' + title}
>
<Text style={styles.buttonText}>{buttonLabel}</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
card: {
padding: 16,
gap: 12,
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#cbd5e1',
borderRadius: 16,
},
detailsPressed: { opacity: 0.7 },
detailsLink: { color: '#1e40af', fontSize: 16, fontWeight: '600' },
bookRow: { minHeight: 48, flexDirection: 'row', alignItems: 'flex-start', gap: 12 },
bookIcon: { fontSize: 28, flexShrink: 0 },
details: { flex: 1, gap: 4 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
author: { color: '#475569', fontSize: 16 },
status: {
alignSelf: 'flex-start',
maxWidth: '100%',
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
backgroundColor: '#e2e8f0',
color: '#334155',
fontSize: 14,
fontWeight: '600',
},
readStatus: { backgroundColor: '#dcfce7', color: '#166534' },
button: {
minHeight: 48,
padding: 12,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1e40af',
borderRadius: 10,
},
buttonPressed: { backgroundColor: '#1e3a8a' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
});
6. Keep Reading List, Retry, and refresh
Once restoration completes, Add Book remains available even if the remote request fails. Refresh replaces only remote results.
import { useRouter } from 'expo-router';
import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import BookCard from '../components/BookCard';
import { useBooks } from '../state/BooksProvider';
export default function HomeScreen() {
const router = useRouter();
const { books, readById, phase, hasLoaded, error, loadBooks, toggleRead } = useBooks();
const busy = phase !== 'idle';
const completedCount = books.filter(book => readById[book.id]).length;
const progressPercent = books.length === 0 ? 0 : completedCount / books.length * 100;
return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<FlatList
data={books}
extraData={readById}
keyExtractor={book => book.id}
refreshing={phase === 'refreshing'}
onRefresh={() => { if (hasLoaded) void loadBooks(true); }}
alwaysBounceVertical
contentContainerStyle={styles.content}
renderItem={({ item }) => (
<BookCard
title={item.title}
author={item.author}
isRead={readById[item.id] ?? false}
onToggleRead={() => toggleRead(item.id)}
onOpenDetails={() => router.push({
pathname: '/books/[id]',
params: { id: item.id },
})}
/>
)}
ListHeaderComponent={
<View style={styles.header}>
<Text style={styles.heading} accessibilityRole="header">My Reading List</Text>
<Text style={styles.body}>Your books and Open Library results</Text>
<Pressable
onPress={() => router.push('/books/add')}
accessibilityRole="button"
accessibilityLabel="Open Add Book form"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Add Book</Text>
</Pressable>
{(hasLoaded || books.length > 0) && (
<>
<Text style={styles.body}>{completedCount} of {books.length} books read</Text>
<View
style={styles.progressTrack}
accessible
accessibilityRole="progressbar"
accessibilityLabel="Reading progress"
accessibilityValue={{ min: 0, max: 100, now: Math.round(progressPercent),
text: `${completedCount} of ${books.length} books read` }}
>
<View style={[styles.progressFill, { width: `${progressPercent}%` }]} />
</View>
</>
)}
{phase === 'loading' && (
<View style={styles.notice}>
<ActivityIndicator size="large" color="#1e40af" accessibilityLabel="Loading books" />
<Text style={styles.body} accessibilityLiveRegion="polite">Loading remote books…</Text>
</View>
)}
{phase === 'refreshing' && (
<Text style={styles.body} accessibilityLiveRegion="polite">Refreshing remote books…</Text>
)}
{error !== null && (
<View style={styles.notice}>
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{hasLoaded ? 'Could not refresh remote books. Keeping your list. ' : 'Remote books are unavailable. You can still add a book. '}{error}
</Text>
<Pressable
onPress={() => { void loadBooks(hasLoaded); }}
disabled={busy}
accessibilityRole="button"
accessibilityLabel="Retry loading books"
accessibilityState={{ disabled: busy }}
style={({ pressed }) => [styles.button, (pressed || busy) && styles.dimmed]}
>
<Text style={styles.buttonText}>Retry loading books</Text>
</Pressable>
</View>
)}
{hasLoaded && error === null && (
<Pressable
onPress={() => { void loadBooks(true); }}
disabled={busy}
accessibilityRole="button"
accessibilityLabel="Refresh books"
accessibilityState={{ disabled: busy }}
style={({ pressed }) => [styles.button, (pressed || busy) && styles.dimmed]}
>
<Text style={styles.buttonText}>Refresh books</Text>
</Pressable>
)}
</View>
}
ItemSeparatorComponent={() => <View style={styles.separator} />}
ListEmptyComponent={hasLoaded && error === null && phase === 'idle' ? (
<View style={styles.notice}>
<Text style={styles.bookTitle}>No books found</Text>
<Text style={styles.body}>No remote matches yet. Use Add Book to create your own entry.</Text>
</View>
) : null}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16, flexGrow: 1 },
header: { gap: 12, marginBottom: 20 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
body: { color: '#334155', fontSize: 16 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
error: { color: '#991b1b', fontSize: 16 },
notice: { padding: 16, gap: 12, backgroundColor: '#ffffff', borderRadius: 16 },
separator: { height: 16 },
progressTrack: { height: 12, borderRadius: 6, backgroundColor: '#cbd5e1', overflow: 'hidden' },
progressFill: { height: '100%', backgroundColor: '#1e40af' },
button: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center',
backgroundColor: '#1e40af', borderRadius: 10 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
dimmed: { opacity: 0.65 },
});
7. Keep the Add Book form
Submission validates and updates the shared list, then returns home. The screen updates before the storage write finishes; this is called an optimistic update. The shared save message tells the reader when it finishes.
import { useRef, useState } from 'react';
import { useRouter } from 'expo-router';
import { useHeaderHeight } from 'expo-router/react-navigation';
import {
Keyboard, KeyboardAvoidingView, Platform, Pressable,
ScrollView, StyleSheet, Text, TextInput, View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useBooks } from '../../state/BooksProvider';
export default function AddBookScreen() {
const router = useRouter();
const headerHeight = useHeaderHeight();
const { addBook } = useBooks();
const [title, setTitle] = useState('');
const [author, setAuthor] = useState('');
const [notes, setNotes] = useState('');
const [attempted, setAttempted] = useState(false);
const titleInput = useRef<TextInput>(null);
const authorInput = useRef<TextInput>(null);
const notesInput = useRef<TextInput>(null);
const submitted = useRef(false);
const titleError = attempted && title.trim().length === 0 ? 'Enter a book title.' : '';
const authorError = attempted && author.trim().length === 0 ? 'Enter an author name.' : '';
function handleSubmit() {
if (submitted.current) return;
setAttempted(true);
const cleanTitle = title.trim();
const cleanAuthor = author.trim();
if (!cleanTitle || !cleanAuthor) {
if (!cleanTitle) titleInput.current?.focus();
else authorInput.current?.focus();
return;
}
// Guard rapid double taps before navigation removes this screen.
submitted.current = true;
addBook(cleanTitle, cleanAuthor, notes.trim());
Keyboard.dismiss();
router.dismissTo('/');
}
function cancel() {
Keyboard.dismiss();
router.dismissTo('/');
}
return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<KeyboardAvoidingView
style={styles.flex}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={headerHeight}
>
<ScrollView
contentContainerStyle={styles.content}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<Text style={styles.heading} accessibilityRole="header">Add to your Reading List</Text>
<Text style={styles.body}>Title and author are required. Notes are optional.</Text>
<View style={styles.field}>
<Text style={styles.label}>Book title (required)</Text>
<TextInput
ref={titleInput}
value={title}
onChangeText={setTitle}
placeholder="Book title"
placeholderTextColor="#64748b"
accessibilityLabel="Book title, required"
accessibilityHint={titleError || 'Enter the title of the book.'}
autoCapitalize="words"
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => authorInput.current?.focus()}
style={[styles.input, titleError !== '' && styles.invalid]}
/>
{titleError !== '' && (
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{titleError}
</Text>
)}
</View>
<View style={styles.field}>
<Text style={styles.label}>Author (required)</Text>
<TextInput
ref={authorInput}
value={author}
onChangeText={setAuthor}
placeholder="Author name"
placeholderTextColor="#64748b"
accessibilityLabel="Author, required"
accessibilityHint={authorError || 'Enter the author name.'}
autoCapitalize="words"
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => notesInput.current?.focus()}
style={[styles.input, authorError !== '' && styles.invalid]}
/>
{authorError !== '' && (
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{authorError}
</Text>
)}
</View>
<View style={styles.field}>
<Text style={styles.label}>Notes (optional)</Text>
<TextInput
ref={notesInput}
value={notes}
onChangeText={setNotes}
placeholder="What would you like to remember?"
placeholderTextColor="#64748b"
accessibilityLabel="Notes, optional"
multiline
autoCapitalize="sentences"
returnKeyType="default"
submitBehavior="newline"
style={[styles.input, styles.notes]}
/>
</View>
<Text style={styles.body}>Books and notes save on this device. Check the save message before closing the app.</Text>
<Pressable
onPress={Keyboard.dismiss}
accessibilityRole="button"
accessibilityLabel="Hide keyboard"
style={({ pressed }) => [styles.secondaryButton, pressed && styles.pressed]}
>
<Text style={styles.secondaryText}>Hide keyboard</Text>
</Pressable>
<Pressable
onPress={handleSubmit}
accessibilityRole="button"
accessibilityLabel="Add Book"
style={({ pressed }) => [styles.button, pressed && styles.pressed]}
>
<Text style={styles.buttonText}>Add Book</Text>
</Pressable>
<Pressable
onPress={cancel}
accessibilityRole="button"
accessibilityLabel="Cancel adding a book"
style={({ pressed }) => [styles.secondaryButton, pressed && styles.pressed]}
>
<Text style={styles.secondaryText}>Cancel</Text>
</Pressable>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
flex: { flex: 1 },
content: { padding: 16, gap: 16, flexGrow: 1 },
heading: { color: '#0f172a', fontSize: 26, fontWeight: '700' },
body: { color: '#334155', fontSize: 16 },
field: { gap: 8 },
label: { color: '#0f172a', fontSize: 16, fontWeight: '600' },
input: { minHeight: 48, padding: 12, borderWidth: 1, borderColor: '#64748b',
borderRadius: 10, backgroundColor: '#ffffff', color: '#0f172a', fontSize: 18 },
notes: { minHeight: 120, textAlignVertical: 'top' },
invalid: { borderColor: '#991b1b', borderWidth: 2 },
error: { color: '#991b1b', fontSize: 16 },
button: { minHeight: 48, padding: 12, borderRadius: 10, backgroundColor: '#1e40af',
alignItems: 'center', justifyContent: 'center' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600' },
secondaryButton: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center' },
secondaryText: { color: '#1e40af', fontSize: 16, fontWeight: '600' },
pressed: { opacity: 0.65 },
});
8. Keep Book Details
Local entries resolve after restoration, including when this route opens directly. Remote entries still depend on the current search. Details reads the same shared status and retains its loading, retry, and missing-book states.
import { useLocalSearchParams, useRouter } from 'expo-router';
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useBooks } from '../../state/BooksProvider';
export default function BookDetailsScreen() {
const { id } = useLocalSearchParams<{ id?: string | string[] }>();
const router = useRouter();
const { books, readById, phase, hasLoaded, error, loadBooks } = useBooks();
const isRemoteId = typeof id === 'string' && /^OL\d+W$/.test(id);
const book = typeof id === 'string'
? books.find(candidate => candidate.id === id) : undefined;
const busy = phase !== 'idle';
function returnToReadingList() {
router.dismissTo('/');
}
return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<ScrollView contentContainerStyle={styles.content}>
<View style={styles.card}>
{book ? (
<>
<Text style={styles.heading} accessibilityRole="header">{book.title}</Text>
<Text style={styles.author}>{book.author}</Text>
<Text style={styles.body}>Status: {readById[book.id] ? 'Read' : 'Unread'}</Text>
{book.notes ? (
<>
<Text style={styles.body} accessibilityRole="header">Notes</Text>
<Text style={styles.body}>{book.notes}</Text>
</>
) : null}
<Text style={styles.body}>Return to your Reading List to change reading progress.</Text>
</>
) : isRemoteId && busy ? (
<>
<ActivityIndicator size="large" color="#1e40af" accessibilityLabel="Loading books" />
<Text style={styles.body} accessibilityLiveRegion="polite">Loading books…</Text>
</>
) : isRemoteId && error !== null ? (
<>
<Text style={styles.body} accessibilityRole="alert">{error}</Text>
<Pressable
onPress={() => { void loadBooks(hasLoaded); }}
accessibilityRole="button"
accessibilityLabel="Retry loading books"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Retry loading books</Text>
</Pressable>
</>
) : (
<>
<Text style={styles.heading} accessibilityRole="header">Book not found</Text>
<Text style={styles.body}>Choose a book from your current Reading List. Remote details are available only for the current search results.</Text>
</>
)}
<Pressable
onPress={returnToReadingList}
accessibilityRole="button"
accessibilityLabel="Return to Reading List"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Return to Reading List</Text>
</Pressable>
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16 },
card: { padding: 16, gap: 12, backgroundColor: '#ffffff', borderWidth: 1,
borderColor: '#cbd5e1', borderRadius: 16 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
author: { color: '#475569', fontSize: 20 },
body: { color: '#334155', fontSize: 16 },
button: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center',
backgroundColor: '#1e40af', borderRadius: 10 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
dimmed: { opacity: 0.65 },
});
Understand failures and limits
| Situation | Behavior and next step |
|---|---|
| No value at the storage key | Start with empty user data; remote books still load. Nothing is written until an edit. |
| Invalid JSON | Show a restoration error and preserve the original text. Retry cannot repair malformed text by itself. |
| Invalid structure, duplicate local IDs, or unknown version | Stop restoration and preserve the record. Do not cast it to the expected type or silently drop entries. |
| Storage read failure | Keep editing blocked and offer Retry restoring data. A failed read is not evidence that no data exists. |
| Storage write failure | Keep changes visible in memory, show the failure, and offer Retry saving. A later successful full snapshot also saves earlier edits. If the latest write fails, the previously stored snapshot may be older. |
| App closes while saving | The latest changes may not reach storage. Wait for “Saved on this device” before the restart exercises. |
| Application data is cleared | The local record is lost; the next launch behaves like a first launch. |
| App is uninstalled and reinstalled | Do not rely on retaining data. Device backup/restore policies can vary; this example implements no backup guarantee. |
| App opens on another device | Start with that device’s own data. No account or synchronization is implemented. |
The single queue coordinates this key within one JavaScript runtime. It does not coordinate several apps, browser tabs, or independent writers. Keep all Reading List writes in the helper. Rapid edits queue multiple full snapshots, which is acceptable for a small teaching app; this is not a large-dataset persistence design. Storage capacity is finite, and failures can still happen.
If restoration remains blocked because the record is damaged, preserve it for inspection before deciding to repair or discard it. A production recovery flow could offer export and confirmed reset; this lesson intentionally does not silently delete user data or introduce a migration framework. version detects an incompatible format but does not migrate it.
Troubleshoot common mistakes
| Symptom | Likely cause or check |
|---|---|
| Saved books vanish immediately at startup | An Effect wrote default state before the read completed. Keep the initialization gate and action-driven writes. |
| Toggling quickly restores an older status later | Writes were launched concurrently, or handlers reused an old state snapshot. Retain the ordered lane and current-value ref. |
| “Saved” appears while the newest edit is still pending | An earlier operation updated the message. Check the latest-save counter. |
| Refresh removes manual entries | Remote and local arrays were combined into a single writable source. Fetch should replace only remoteBooks. |
| A new local entry replaces an old one | The ID counter reset without checking restored IDs. Keep the collision check. |
| Remote status appears missing | That ID may not be in this search result. Preserve its map entry; do not prune status on refresh. |
| JSON parses but the app crashes later | Parsing was mistaken for validation. Treat the parsed value as unknown until its fields are checked. |
createAsyncStorage is unavailable | This lesson installs 2.2.0. Use its default import; do not mix version 3 examples into it. |
| Native storage module cannot be found | Check the SDK-compatible package and Expo Go version, or rebuild your custom development client. |
The storage key contains [object Object] | An object was coerced to text instead of serialized with JSON.stringify. |
| Local details says “Book not found” before restoration | A screen was allowed to mount while the provider was still reading storage. |
Do not put setItem inside render or a functional state updater. Do not use an array index as an ID. Do not catch a restoration error and return an empty list: that turns unreadable saved data into apparently valid empty state, which a later edit could overwrite.
Practice
These are learner activities, not claims that the application was executed for this publication.
- Restore a manual book. Add a title, author, and notes. Wait for the saved message, fully close and reopen the app, and open its Details. Refresh remote results and verify that the local entry remains. This should also work when remote fetching fails.
- Restore reading decisions. Mark a local and a remote book read, then toggle one rapidly a few times. Wait for saving, restart, and compare the final status. A remote status can only be displayed if its ID is present in the current results.
- Clear Reading Progress with confirmation. Add an action that asks before resetting only
readById; preserve manually added books and notes. Send the resulting snapshot through the same ordered writer and show failures. Decide what Cancel should do and how to avoid bypassing the restoration guard. Do not clear unrelated storage keys.
Check your understanding
- Why does state survive navigation but not a full app restart?
- Why persist local books and statuses, but not the whole API response?
- How do a missing key, invalid JSON, and an invalid saved structure differ?
- What prevents the initial empty list from overwriting an existing saved list?
- Why must writes be ordered even when every individual call uses
await? - What happens when an earlier save fails but a newer complete snapshot succeeds?
- Why does the provider check restored local IDs when generating a new one?
- Does “Saved on this device” mean encrypted, backed up, or synchronized?
Compare your answers
The provider remains mounted during navigation, but restarting recreates memory. Local entries and reading decisions belong to the reader; remote metadata can be fetched again. A missing key returns null, malformed JSON cannot be parsed, and a wrong structure can be valid JSON with unusable fields. The provider starts unrestored, blocks edits, and never writes just because initialization ran. Separate async functions can overlap even if each awaits its own write, so the shared queue orders them. A later full snapshot includes earlier in-memory changes; if it succeeds, the newest list is saved. The counter resets on restart, so restored IDs must also be checked. Saving locally provides none of encryption, guaranteed backup, or cross-device synchronization.
You are ready to continue when: Your added books and final reading status return after a restart, remote refresh preserves them, and you can explain why a storage failure must stay visible.
Return to the learning path. Cloud synchronization, large datasets, schema migrations, and form-draft recovery are outside this lesson.