Networking & APIs
Fetch REST and GraphQL data, handle errors, loading states, and caching in mobile networks.
Fetch and Axios
fetch API works in React Native for HTTP requests. Always await response.json() inside try/catch and check response.ok before parsing.
Axios adds interceptors, timeouts, and automatic JSON transforms. Configure baseURL and auth headers centrally.
Mobile networks are flaky—retry idempotent GETs with backoff and surface offline UI with NetInfo.
- Set reasonable timeouts—mobile users wait less than desktop
- Cancel requests on unmount with AbortController
- Pin TLS certificates only with clear rotation plan
async function loadProducts() {
const res = await fetch('https://api.example.com/products');
if (!res.ok) throw new Error('Request failed');
return res.json();
}TanStack Query
TanStack Query (React Query) caches API responses, deduplicates in-flight requests, and refetches on focus or reconnect.
Query keys identify cache entries. Mutations invalidate queries after POST/PUT. Optimistic updates improve perceived speed for likes and toggles.
Prefetch data on navigation hover equivalents—call prefetchQuery before navigate on Pressable onPressIn.
- Stale-while-revalidate defaults suit many list screens
- Use enabled: false until auth token available
- Persist cache sparingly—respect sensitive data