React components render synchronously from the data already in memory, and a network request cannot finish during that first render. A component that calls an API therefore needs to show something immediately, fire the request after mounting, and update when the response arrives. That two-phase flow is asynchronous data fetching in React.
The baseline pattern uses two hooks. useState holds the data, a loading flag, or an error. useEffect runs the fetch after the component renders and re-runs it when a dependency changes. That pattern works, but it leaves four problems unsolved: it refetches the same data on every mount, it shows outdated data while a slow request finishes, it leaves requests running after the component unmounts, and it has no recovery from failures. Each problem has a solution. The caching strategy behind the SWR and TanStack Query libraries serves data instantly and refreshes it in the background. React 19’s async features move fetching and pending-state handling into the framework. AbortController is a browser API that cancels a fetch request. Using it to cancel requests during cleanup, and retrying failed requests, keeps requests from leaking and gives users a way to recover when a request fails.
The baseline: useState, useEffect, and fetch
When you fetch in a function component, the request runs inside an effect because the component body executes during render, where you cannot await a network call. The standard shape keeps three pieces of state: the data, a flag for whether the request is still running, and the error if one occurred.
import { useState, useEffect } from "react";
function Profile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => response.json())
.then((data) => setUser(data))
.catch((err) => {
if (err.name !== "AbortError") setError(err);
});
return () => controller.abort();
}, [userId]);
if (error) return <p>Could not load the user.</p>;
if (!user) return <p>Loading...</p>;
return <p>{user.name}</p>;
}
The useEffect dependency array controls when React re-runs the effect. React compares the array to the previous render’s array, and when any entry changes, it cleans up the old effect and runs the new one. Here the cleanup aborts the in-flight request, so a response that arrives after the component unmounted or after userId changed cannot update a component that no longer exists. That cleanup separates a working fetch from a memory leak: timers, event listeners, WebSockets, and pending requests all keep running after the component disappears unless the effect disposes of them. AbortController is the right tool for fetch specifically, because abort() cancels the network request rather than only ignoring its result. React’s Strict Mode runs effects twice in development, so write the cleanup so it tolerates being called early and repeatedly.
A note on the catch: fetch rejects for network failures and for aborted requests, and an abort produces an AbortError. If you set state for every rejection, an aborted request can still update a dead component, so check the error name. This is one of the places where handling fetch errors in frontend applications most often goes wrong.
The base pattern refetches everything, and that is the first problem
Every mount of the component above triggers a fresh request. Navigate to a different route and back, and the component fetches again even when nothing changed. The UI flashes a loading state, and the server handles a request it answered moments ago. For a single screen that cost is small; across a product catalog, a dashboard, or a list view with repeated visits, it adds up.
The second problem is latency. A slow request leaves the user staring at a loading state for its full duration on every visit. The fix is to serve data the user already saw while a background refresh runs, a strategy called stale-while-revalidate.
Stale-while-revalidate: serve what you have, refresh in the background
Stale-while-revalidate is an HTTP caching strategy: the cache serves content immediately, even when it is past its freshness window, and refreshes the cache in the background so the next request gets newer data. The Cache-Control response header sets the timing. max-age marks how long content stays fresh. stale-while-revalidate sets how much longer past that the cache may serve stale content while it revalidates. The sum of the two values is the maximum allowed staleness. A header of Cache-Control: max-age=60, stale-while-revalidate=300 serves content under 60 seconds old as fresh, serves content between 60 and 360 seconds old as stale with a background refresh, and fetches content older than 360 seconds directly from the origin. All modern browsers support the instruction, with Chrome from version 75, Edge from version 79, Safari from version 14, and Firefox from version 68.
For API calls, the HTTP version does not do what you want. When the browser handles a stale-while-revalidate response, it returns either the cached copy or the fresh response, not both, which conflicts with wanting fresh data on every API request. The React libraries named after the strategy implement a client-side variant that behaves differently: the library returns the cached data to the component immediately, fires the request in the background, and swaps in the fresh data when it arrives. The user sees an instant UI, and the component settles to correct data moments later.
This strategy fits data that changes occasionally and tolerates brief staleness: user profiles, product catalogs, configuration data, CMS content, and non-critical dashboards. It does not fit data that must be current to the second, including accurate inventory levels, reservation availability, live auction prices, sports scores, session tokens, login status, and collaborative views. Using it for those cases serves outdated information.
SWR and TanStack Query: two takes on the same idea
Both major libraries implement client-side stale-while-revalidate. SWR, created by Vercel, takes its name from the HTTP strategy and offers a small, unopinionated API: you give it a key and a fetcher, and it returns the data plus a way to mutate it. TanStack Query, formerly React Query, is the larger library. The project rebranded and merged React Query into TanStack Query, so code still on the old package should move to the new one.
The practical differences show up in caching and mutations. TanStack Query separates staleTime, how long data counts as fresh, from cacheTime, how long inactive data stays in memory, so you control each independently. SWR ties caching to the key you pass and, by default, revalidates when the window regains focus, when the network reconnects, and on a set interval. For writes, SWR exposes a mutate function that updates the local cache immediately and then revalidates. TanStack Query treats mutations as first-class operations through useMutation, with structured side-effect handling and query invalidation built in. TanStack Query also ships a devtools panel that visualizes the query cache and triggers refetches; SWR has no official equivalent.
The choice is about complexity. SWR fits straightforward applications, tight bundle-size budgets, and codebases already invested in the Vercel and Next.js ecosystem. TanStack Query earns its weight when queries depend on each other, pagination is intricate, mutations are complex, or the application is large enough that cache inspection and structured invalidation matter. If you are deciding whether to hand-roll a hook or pull in a library, choosing between fetch and a client library comes down to how much of this machinery you want to own.
React 19: async support built into the framework
React 19 moved several of these concerns into the framework. Actions are async functions that integrate directly with forms and buttons; the framework manages pending state, error handling, and optimistic updates (showing the expected result before the server confirms it) for you. The use hook lets a component await a promise directly and suspend rendering until the data arrives, which is the intended pattern in Server Components. useOptimistic updates the UI with the expected result immediately and reconciles with the server response when it lands.
Server Components are stable and official in React 19. A Server Component can be an async function that fetches with the Fetch API directly, without useState, useEffect, or a separate API route. The server renders the page fully before sending it, which helps first paint, cuts client-side computational load, keeps the HTML populated for search engines, and keeps sensitive data and business logic off the client. Paired with Server Actions, you can run backend logic from the frontend without standing up an API endpoint.
Suspense, the mechanism that pauses rendering until data is ready, controls how the UI waits. Wrap the whole page in a coarse boundary and nest fine boundaries around the slower regions, so the page paints quickly while the slow parts resolve in place. Kick off several requests together and consume them where needed, so the requests overlap instead of forming a waterfall where each waits on the previous one. For filters and search, wrap background refreshes in startTransition so typing and clicks stay responsive while the data settles a moment later.
Cancellation, retries, and recovery
The cleanup pattern from the baseline extends to every approach. Tie each request to an AbortController and cancel it on unmount, on a route change, or when a newer request supersedes it. That stops the application from finishing work no one can see and prevents late arrivals from rendering the wrong data. In Strict Mode’s double-run, the cleanup runs twice, so it must not assume a single lifecycle.
When a request fails, retry with exponential backoff, doubling the delay between attempts. A fetchWithRetry utility starts at a 1-second delay, then waits 2 seconds, then 4, which gives transient network issues time to clear without hammering the server. For authenticated requests, refresh tokens let the client quietly obtain a new access token when the current one expires, instead of forcing a re-login. A proactive approach that refreshes before expiration, for example when the token is within five minutes of expiring, reduces session-related failures.
Recovery matters as much as the retry. An error boundary should tell the user what happened and give them a path forward: retry the request, go back, or fall back to cached data. A generic failure message leaves the user with no action and no information. CORS (Cross-Origin Resource Sharing) is a browser security rule that restricts which origins can read a response. When the failure comes from a network-level condition like CORS, the fix is usually in the server configuration, and the error message should reflect that the request never completed rather than pretending the server returned bad data. Why fetch requests fail because of CORS covers the common causes.
Server-side caching in Next.js
When you fetch inside a Next.js route or Server Component, the framework gives you cache control that client-side libraries cannot touch. The fetch function in Next.js accepts cache options, including default, no-store, reload, no-cache, force-cache, and only-if-cached, plus the [next.revalidate](https://infinum.com/handbook/frontend/react/recipes/caching-and-revalidation) option, which tells Next.js how long to keep the cached version before revalidating in the background. Incremental Static Regeneration generates pages at build time and revalidates them incrementally when requested again: after the revalidate period passes, the next incoming request triggers a background regeneration. On-demand revalidation lets an external event, usually a CMS update, invalidate cached pages immediately instead of waiting for the window to close, and it can target whole sections, specific paths, or tagged entries.
Where you trigger revalidation matters. Revalidating in the API route is the production-preferred approach over revalidating in a Server Action, because it centralizes cache invalidation with the data mutation, so any client that calls the API gets consistent behavior. A shared cache is the main risk: in a server-rendered application, a module-level cache is shared across requests, so cached data from one user could become visible to another. Server-side caches must be created separately for each request.