Data Retrieval Techniques and Libraries
How data-fetching approaches evolved from local state patterns to server-state libraries.
Data Retrieval Techniques and Libraries
How data-fetching approaches evolved from local state patterns to server-state libraries.
A common traditional pattern for external data in React is useEffect -> fetch -> store results in local state. Each component triggers a request in useEffect, tracks loading, error, and data with useState, and renders from that local state.
This works well for simple cases, but as apps grow it can duplicate request logic and make caching, retries, and refetch consistency harder to manage across screens.
Modern server-state tools like TanStack Query keep the same React component model while centralizing cache, staleness, retries, and invalidation. This reduces boilerplate and improves consistency.
Other approaches were also common, including Redux thunks and sagas, custom hooks, SWR, Apollo, and similar solutions.
In React Query, QueryClient manages all queries and mutations in the app. It is created once and passed to QueryClientProvider at the root of the application. defaultOptions is a convenient place to define global defaults for all queries.
Why this approach is useful
- Centralized server-state lifecycle: loading, error, success, caching, and retries are standardized.
- Cache reuse across screens: multiple components can read the same query key without duplicate requests.
- Better UX defaults: staleTime, retry, and refetch behavior can be tuned globally.
- Less boilerplate in pages: components focus on UI and intent, not request orchestration details.
- Easier invalidation after writes: mutations can refresh only affected queries.
- Traditional local-state fetching still works, but often leads to repeated fetching logic, duplicated loading and error handling, and inconsistent caching behavior.
