Nine spreads on mobile development: how phones run apps, UI and navigation, state, data and offline, native features, performance, testing, and publishing to the stores. Examples use React Native with Expo.
"Expo and React Native with typed navigation, server state in React Query, offline-first storage, OTA updates, and CI builds through EAS."
Use the tabs or the ← → keys.
$ node -v # Node 20+ $ npx create-expo-app@latest my-app --template blank-typescript $ cd my-app && npx expo start # scan the QR with the Expo Go app on your phone $ npx expo start --ios ; npx expo start --android # simulator / emulator (needs Xcode / Android Studio)
// App.tsx: the smallest useful screen
import { useState } from "react";
import { View, Text, Pressable, StyleSheet } from "react-native";
export default function App() {
const [count, setCount] = useState(0);
return (
<View style={styles.container}>
<Text style={styles.title}>Taps: {count}</Text>
<Pressable accessibilityRole="button" onPress={() => setCount(c => c + 1)} style={styles.button}>
<Text style={styles.buttonText}>Tap me</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, alignItems: "center", justifyContent: "center", gap: 16 },
title: { fontSize: 28, fontWeight: "700" },
button: { backgroundColor: "#2f5bea", paddingVertical: 14, paddingHorizontal: 28, borderRadius: 12 },
buttonText: { color: "white", fontSize: 18 },
});
"Assume the OS can kill the app any time, so state is saved and restored, and everything works offline first."
import { FlatList, View, Text, SafeAreaView, Image, ActivityIndicator } from "react-native";
type Task = { id: string; title: string; done: boolean };
function TaskRow({ task }: { task: Task }) {
return (
<View style={{ flexDirection: "row", alignItems: "center", padding: 16, gap: 12 }}>
<Text style={{ fontSize: 18, textDecorationLine: task.done ? "line-through" : "none" }}>{task.title}</Text>
</View>
);
}
export function TaskList({ tasks, loading }: { tasks: Task[]; loading: boolean }) {
if (loading) return <ActivityIndicator />;
return (
<SafeAreaView style={{ flex: 1 }}>
<FlatList
data={tasks}
keyExtractor={t => t.id}
renderItem={({ item }) => <TaskRow task={item} />}
ListEmptyComponent={<Text style={{ padding: 24 }}>Nothing yet. Add a task.</Text>}
ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: "#8884" }} />}
/>
</SafeAreaView>
);
}
useColorScheme), large text, and screen readers (accessibilityLabel).KeyboardAvoidingView) and safe areas."FlatList for lists, safe areas respected, dark mode and accessibility labels from the start."
$ npx expo install @tanstack/react-query expo-secure-store @react-native-async-storage/async-storage zustand
import { QueryClient, QueryClientProvider, useQuery, useMutation } from "@tanstack/react-query";
import * as SecureStore from "expo-secure-store";
const API = process.env.EXPO_PUBLIC_API_URL; // set in .env; EXPO_PUBLIC_ is bundled into the app (public!)
async function api<T>(path: string, init?: RequestInit): Promise<T> {
const token = await SecureStore.getItemAsync("token");
const res = await fetch(API + path, { ...init, headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, ...init?.headers } });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
export function useTasks() {
return useQuery({ queryKey: ["tasks"], queryFn: () => api<Task[]>("/tasks"), staleTime: 30_000 });
}
export function useAddTask(qc: QueryClient) {
return useMutation({
mutationFn: (title: string) => api<Task>("/tasks", { method: "POST", body: JSON.stringify({ title }) }),
onSuccess: () => qc.invalidateQueries({ queryKey: ["tasks"] }), // refetch the list
});
}
"React Query for server state, SecureStore for tokens, and no secrets inside the binary."
import * as SQLite from "expo-sqlite";
import NetInfo from "@react-native-community/netinfo";
const db = await SQLite.openDatabaseAsync("app.db");
await db.execAsync(`
CREATE TABLE IF NOT EXISTS tasks (id TEXT PRIMARY KEY, title TEXT NOT NULL, done INTEGER DEFAULT 0, updated_at INTEGER);
CREATE TABLE IF NOT EXISTS outbox (id TEXT PRIMARY KEY, op TEXT NOT NULL, payload TEXT NOT NULL);
`);
async function addTask(title: string) {
const id = crypto.randomUUID(); // client-made ID → safe to retry
await db.runAsync("INSERT INTO tasks (id, title, updated_at) VALUES (?, ?, ?)", id, title, Date.now());
await db.runAsync("INSERT INTO outbox (id, op, payload) VALUES (?, 'create_task', ?)", id, JSON.stringify({ id, title }));
void flushOutbox(); // try now; harmless if offline
}
async function flushOutbox() {
if (!(await NetInfo.fetch()).isConnected) return;
for (const row of await db.getAllAsync<{ id: string; payload: string }>("SELECT * FROM outbox")) {
const res = await fetch(`${API}/tasks`, { method: "POST", headers: { "Idempotency-Key": row.id }, body: row.payload });
if (res.ok) await db.runAsync("DELETE FROM outbox WHERE id = ?", row.id);
else break; // stop, retry later
}
}
NetInfo.addEventListener(s => { if (s.isConnected) void flushOutbox(); });
"Local-first writes with an outbox, idempotency keys, sync on reconnect, and visible sync status."
$ npx expo install expo-camera expo-location expo-notifications expo-local-authentication expo-image-picker
import * as Location from "expo-location";
import * as Notifications from "expo-notifications";
import * as LocalAuth from "expo-local-authentication";
async function nearbyStores() {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== "granted") return showFallback("Enter your postcode instead"); // handle denial gracefully
const pos = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced });
return fetchStores(pos.coords.latitude, pos.coords.longitude);
}
async function registerForPush() {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== "granted") return null;
const token = (await Notifications.getExpoPushTokenAsync()).data; // send this to your server
return token;
}
async function confirmWithBiometrics() {
const ok = (await LocalAuth.authenticateAsync({ promptMessage: "Confirm payment" })).success;
return ok;
}
app.json → ios.infoPlist); stores reject vague reasons."Permissions asked in context with a fallback path, push tokens stored server-side, and biometrics for sensitive actions."
import { memo, useCallback } from "react";
import { FlashList } from "@shopify/flash-list";
import { Image } from "expo-image"; // caching, placeholders, fast decoding
const Row = memo(function Row({ item, onPress }: { item: Task; onPress: (id: string) => void }) {
return <Pressable onPress={() => onPress(item.id)}><Text>{item.title}</Text></Pressable>;
});
export function Tasks({ tasks }: { tasks: Task[] }) {
const open = useCallback((id: string) => router.push(`/tasks/${id}`), []);
return <FlashList data={tasks} estimatedItemSize={56} keyExtractor={t => t.id}
renderItem={({ item }) => <Row item={item} onPress={open} />} />;
}
$ npx expo start --no-dev --minify # test a production-like bundle; dev mode is much slower $ npx expo-doctor # dependency and config health check # profile: React DevTools Profiler · Flipper/Hermes profiler · Xcode Instruments · Android Studio Profiler
"Virtualized lists, memoized rows, cached resized images, and profiled on a mid-range device in release mode."
$ npx expo install jest-expo jest @testing-library/react-native $ npx jest --watch
import { render, screen, fireEvent } from "@testing-library/react-native";
import App from "../App";
test("increments the counter when tapped", () => {
render(<App />);
fireEvent.press(screen.getByRole("button", { name: /tap me/i }));
expect(screen.getByText("Taps: 1")).toBeTruthy();
});
# .maestro/login.yaml : end-to-end flow on a real device or emulator (Maestro) appId: com.acme.app --- - launchApp - tapOn: "Email" - inputText: "test@example.com" - tapOn: "Sign in" - assertVisible: "Welcome"
$ maestro test .maestro/login.yaml
"Logic unit-tested, screens component-tested, key flows run by Maestro in CI, and releases staged with crash monitoring."
$ npm i -g eas-cli && eas login $ eas build:configure $ eas build --platform all --profile production # cloud builds, no Mac needed for iOS builds $ eas submit --platform ios # → App Store Connect / TestFlight $ eas submit --platform android # → Play Console $ eas update --branch production --message "Fix login typo" # OTA JS update
// eas.json
{ "build": {
"development": { "developmentClient": true, "distribution": "internal" },
"preview": { "distribution": "internal" },
"production": { "autoIncrement": true }
},
"submit": { "production": {} } }
// app.json essentials
{ "expo": { "name": "My App", "slug": "my-app", "version": "1.0.0", "scheme": "myapp",
"ios": { "bundleIdentifier": "com.acme.myapp", "buildNumber": "1" },
"android": { "package": "com.acme.myapp", "versionCode": 1 } } }
"EAS builds in CI, beta through TestFlight and Play testing, staged rollout, and OTA updates for JS-only fixes."