Networking Clients & Server-state Caching

Make typed API calls with fetch, Dio, Retrofit or URLSession, and cache server data with tools like TanStack Query.

Intermediate · about 8 hours · difficulty 3/5

Learn first: HTTP & REST APIs for App Developers, State Fundamentals

Calling an API is easy; handling loading, errors, retries, caching and refetching well across dozens of screens is the real work.

Clients by stack

  • React Native: fetch or axios, wrapped in a small typed API module.
  • Flutter: dio (interceptors, cancellation) or http.
  • Android: Retrofit or Ktor with kotlinx.serialization.
  • iOS: URLSession with Codable.

Centralise the base URL, auth header injection, timeouts and error mapping in one place (interceptors), so screens only call api.getOrders().

Server-state caching

TanStack Query (React Native) treats API data as a cache keyed by query: useQuery({ queryKey: ["orders"], queryFn: api.getOrders }). It handles loading and error states, deduplicates requests, refetches when the app returns to the foreground, and supports pagination and optimistic updates via useMutation. Flutter's Riverpod FutureProvider, and repository patterns on native, fill the same role.

Pitfalls

  • Parsing JSON without validation; the app crashes when the backend changes a field.
  • Showing a spinner on every refetch instead of keeping stale data visible.
  • Forgetting to refresh tokens, so users are logged out randomly.

Good enough to move on: your screens get data through a typed client and a query cache with loading, error, retry and pull-to-refresh.

Key concepts

  • Typed API client module
  • Interceptors for auth and errors
  • Timeouts, retries and cancellation
  • TanStack Query: React Native
  • Dio, Retrofit or URLSession: Flutter and native
  • Optimistic updates
  • Refetch on focus and reconnect

Mini project

Build a movie browser with search, infinite scroll and a favourite button that updates optimistically and rolls back on failure.

Check yourself

Why is keeping stale data on screen while refetching usually better than showing a full-screen spinner?

Free resources