Sub topic 16
Choosing an approach
This chapter assumes you know promises and async/await, React components and props, useState and useEffect, and basic HTTP (methods, status codes, JSON). It also assumes you have seen the earlier chapters on effect-based fetching, TanStack Query, mutations, Suspense, and Server Components. Here you will use that material to decide which approach fits a given situation.
The three options
React gives you three broad ways to get data into a component.
- Effect-based fetching. You call
fetchinsideuseEffectand keep the request state inuseState, either in the component or in a custom hook such asuseFetch. - A server-state library. You use TanStack Query (or a similar library) to own the request, the cache, and the refetching.
- Framework-level fetching. A framework that supports Server Components lets an async component
awaitdata on the server. Suspense and theusehook cover the related case where a client component reads a promise.
These options are not mutually exclusive. A single application often uses all three in different places.
What each approach costs
Every approach has a price. The table summarizes what you get and what you give up.
| Approach | You get | You give up |
|---|---|---|
| `useEffect` plus `useState` | No dependencies, full control, easy to read for one request | You write loading, error, cleanup, and race handling yourself. No cache, no deduplication, no automatic refetching |
| TanStack Query | Caching by query key, deduplication, staleness rules, refetching, mutations with invalidation | An added dependency, concepts to learn (keys, staleness, invalidation), and a provider to set up |
| Server Components | No client-side state for the initial load, data fetched next to the code that uses it, less JavaScript sent to the browser | Requires a supporting framework and a server. The component cannot use state or effects. Client interactions still need another tool |
Effect-based fetching: when it is enough
Effect-based fetching is a reasonable choice when all of these hold:
- One component, or a few, need the data, and nothing else shares it.
- You do not need to show cached data when the user returns to the screen.
- You do not need background refetching, polling, or retries.
- The app has no existing data library, and the extra dependency is not justified for one or two requests.
Examples are a small internal tool, a prototype, a one-off widget on a mostly static page, or a learning project. If you choose this path, treat the following as required, not optional:
- Check
response.ok, becausefetchonly rejects on network failure and not on a 404 or 500. - Track loading, error, and success states.
- Abort in the effect cleanup, so a slow earlier response cannot overwrite a newer one.
- Move the logic into a hook once a second component needs it.
The hook from earlier in the tutorial follows all four rules:
import { useEffect, useState } from 'react';
export function useFetch(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => setState({ status: 'success', data, error: null }))
.catch((error) => {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
});
return () => controller.abort();
}, [url]);
return state;
}Signs you have outgrown effects
Watch for these symptoms. Each one maps to a limit of effect-based fetching.
- The same data is requested from several components. Each component sends its own request, and nothing deduplicates them.
- Navigating back shows a spinner again. Component state is lost on unmount, so there is no cache.
- You want data to refresh when the window regains focus, or on an interval. You would have to build this yourself.
- Users edit data and other screens must update. You end up passing refetch callbacks around.
- Your hook keeps growing. Retries, pagination, and optimistic updates are signs you are rebuilding a library.
When two or more of these appear, move to a library. Rewriting is usually small, because the queryFn is the same fetch logic you already had.
TanStack Query: the default for interactive client data
For data that users read and change in the browser, a server-state library is usually the better fit. The query key identifies and caches the data, and the library handles loading, errors, and cancellation signals.
import { useQuery } from '@tanstack/react-query';
async function fetchUser(userId, signal) {
const response = await fetch(`/api/users/${userId}`, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
function UserProfile({ userId }) {
const { data, error, isPending } = useQuery({
queryKey: ['user', userId],
queryFn: ({ signal }) => fetchUser(userId, signal),
});
if (isPending) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{data.name}</h1>;
}Choose a library when you need any of these:
- Shared data across components, with one request instead of many.
- Control over how long data counts as fresh, through staleness settings.
- Mutations that update the server and then invalidate related queries.
- Consistent loading and error handling across a large app.
Two cautions apply. First, the library does not remove the need for response.ok checks, since your queryFn must throw on bad statuses. Second, a poorly designed query key causes wrong cache hits. Include every value the request depends on, such as userId, in the key.
Server Components: fetch where the data lives
In a framework that supports React Server Components, an async component can await a fetch directly and render the result, with no effect or client-side state.
export default async function UserList() {
const response = await fetch('https://example.com/api/users');
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const users = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}This suits content that is mostly read: lists, article pages, dashboards that load once. The data arrives with the first HTML, there is no loading state in the client, and secrets such as API keys stay on the server.
Server Components do not replace client tools for everything. A component that must refetch on a button click, poll, or run a mutation still needs client code. Many applications combine the two. The server renders the initial view, and a client component using TanStack Query takes over for live updates.
Suspense and the use hook
Suspense lets a component wait for data while React shows a fallback. The use hook reads a promise during render. Neither one creates a cache. If you create a new promise on every render, you start a new request on every render. The promise must come from a stable place, such as a Server Component passing it down, or a library that manages caching. Treat Suspense as a way to organize loading UI, and still decide separately where the data and its cache live.
Suspense also helps with request waterfalls. Components that fetch in parallel under separate Suspense boundaries show their results as each one arrives, instead of one after another.
Decision criteria
Ask these questions in order.
- Does your framework support Server Components, and is the data mostly read? Fetch on the server first.
- Is the data shared, edited, or refreshed in the browser? Use TanStack Query.
- Is it one simple request in a small app? Use
useEffect, preferably inside auseFetchhook. - Are you unsure? Start with the simplest option that meets today's needs. The
fetchlogic moves between approaches with little change.
Common mistakes when choosing
- Adding a library to a one-request prototype, which adds setup cost with no benefit.
- Growing a
useFetchhook to handle caching and retries instead of adopting a library. - Assuming Server Components remove the need for error handling. They still throw on bad responses, and you still need error boundaries.
- Treating
useor Suspense as a data cache. - Fetching a list in a parent and then each item in a child effect, which creates a waterfall. Fetch in parallel or move the request up.
Exercise
A team builds an admin screen. A table of orders appears on several tabs, users edit an order in a dialog, and every tab must show the change right away. The app uses a framework without Server Components. Which approach fits, and which two TanStack Query features solve the main problems?
Show answer
Use TanStack Query. A shared query key (for example ['orders']) lets all tabs use one cached request. A mutation sends the edit, and invalidating the 'orders' query in onSuccess re-fetches the data so every tab updates. Effect-based fetching would need manual refetch callbacks and would load the data separately in each tab.
Exercise
A marketing page shows a list of blog posts that changes rarely. It has no interactive editing. The framework supports Server Components. Which approach fits, and why is a client-side effect a weaker choice?
Show answer
Fetch in an async Server Component. The posts arrive with the initial render, no loading state or client JavaScript is needed for the fetch, and API keys stay on the server. An effect would load the data only after the page's JavaScript runs, adds loading and error state to manage, and makes the page show a spinner first.