Sub topic 10
Where Effect-Based Fetching Falls Short
This chapter assumes you can write a component that fetches inside useEffect, model loading, error, and success states, and cancel stale requests with AbortController. It also assumes you have seen the useFetch hook from the previous chapters. Here you will see what that approach still does not give you, and why those gaps push teams toward a dedicated data library.
What the hook solves, and what it leaves open
A useFetch hook removes duplicated code. It also handles cancellation and the three request states. These are real wins. But the hook only knows about one component instance and one request at a time. Everything below follows from that fact.
The problems fall into five groups:
- No shared cache, so the same data is fetched again and again.
- No request deduplication, so simultaneous components fire identical requests.
- No built-in refetching, so data goes stale without anyone noticing.
- No retries, so one network blip becomes a permanent error screen.
- No coordination after writes, so the UI shows old data after a change.
Each one is manageable alone. Together, they mean you end up writing a small data library inside your app.
No cache: every mount starts from zero
State created with useState lives and dies with the component. When the component unmounts, the data is gone. Mounting it again starts a new request and shows the loading state again.
Consider a list page and a detail page. A user opens a profile, goes back to the list, and opens the same profile again. With effect-based fetching, the second visit shows "Loading..." and repeats a request that returned seconds ago.
import { useFetch } from './useFetch';
function ProfilePage({ userId }) {
const state = useFetch(`/api/users/${userId}`);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error.message}</p>;
return <h1>{state.data.name}</h1>;
}Every time ProfilePage mounts, useFetch resets to status: 'loading' and data: null. The hook also clears old data when url changes. That is correct for avoiding a mismatch between the URL and the data, but it means the user never sees previously loaded content while new content arrives.
No deduplication: identical requests in parallel
Suppose a header shows the current user's name and a sidebar shows their avatar. Both call useFetch('/api/me'). Each component has its own state and its own effect, so the browser sends two identical requests.
import { useFetch } from './useFetch';
function Header() {
const { data } = useFetch('/api/me');
return <span>{data ? data.name : '...'}</span>;
}
function Sidebar() {
const { data } = useFetch('/api/me');
return <img alt="" src={data ? data.avatarUrl : ''} />;
}With five components, you get five requests. The responses may also differ if the server data changes between them, so two parts of the screen can briefly disagree.
You can fix this by lifting the fetch into a parent and passing data down, or by storing it in context. Both work, but they couple your component tree to your data needs. You also still have to decide when the shared value is refreshed.
No refetching: data goes stale silently
A component fetches once per effect run. The effect re-runs only when a dependency changes. Nothing in the hook notices that:
- The user left the tab and came back an hour later.
- The network dropped and reconnected.
- Another user changed the record on the server.
To handle these, you add more code. You listen for visibilitychange or online events, or start a setInterval for polling. Each addition needs its own cleanup and its own handling of overlap, such as a poll firing while a previous request is still running.
import { useEffect, useState } from 'react';
function useRefetchOnFocus(refetch) {
useEffect(() => {
function onVisible() {
if (document.visibilityState === 'visible') refetch();
}
document.addEventListener('visibilitychange', onVisible);
return () => document.removeEventListener('visibilitychange', onVisible);
}, [refetch]);
}
export function useCounter() {
const [count, setCount] = useState(0);
useRefetchOnFocus(() => setCount((c) => c + 1));
return count;
}The sketch above shows only the listener plumbing. To make useFetch use it, you would have to change the hook to expose a refetch function, keep that function's identity stable, and decide whether refetching shows a loading state or keeps old data visible. That is real design work, repeated per project.
No retries or backoff
A single failed request currently produces a permanent error state. For transient failures, such as a dropped connection or a 503, a good client retries a few times with growing delays. Writing this by hand means a loop with timers, cancellation of those timers on cleanup, and a rule about which errors are worth retrying. A 404 should not be retried. A 503 usually should.
Writes leave the UI out of date
Effects handle reads. They say nothing about writes. After a PATCH request changes a user's name, the data in your useFetch state is still the old name. You have three options, and each has a cost:
- Refetch the data after the write. This is simple but costs an extra round trip.
- Update local state by hand. This is fast, but every component that holds a copy of that user must be updated too.
- Reload the page. This is reliable but discards the user's context.
Because each component owns a private copy, option 2 is hard. You need a way to tell other components that their copy is out of date. That mechanism is a cache with invalidation, which useFetch does not have.
Subtle correctness issues that remain
Even with cleanup, some problems persist:
- Flash of empty content. Resetting to
loadingon every URL change replaces useful content with a spinner, even when the user is only paging through results. - Unstable dependencies. If you pass an options object or inline function into the hook and list it as a dependency, the effect re-runs on every render. This can create a request loop.
- Error handling is per call site. Each component decides how to show errors. There is no central place to log failures or react to a
401by redirecting to login. - Late fetching. The effect runs only after the component renders and the browser paints. A child that fetches in its own effect cannot start until its parent has rendered it. This creates the request waterfalls covered in an earlier chapter.
- No server rendering. Effects do not run on the server. Content fetched in an effect is never part of server-rendered HTML.
The gap, summarized
The table maps each need to what effect-based fetching offers and what a data library adds.
| Need | Effect + `useFetch` | Server-state library |
|---|---|---|
| Cancel stale requests | Yes, with `AbortController` | Yes, signal passed to the query function |
| Loading and error states | Yes, by hand | Yes, built in |
| Share data between components | No, unless you add context | Yes, through a shared cache |
| Deduplicate identical requests | No | Yes, by query key |
| Show cached data while refreshing | No | Yes |
| Refetch on focus or reconnect | No, hand-written | Yes, configurable |
| Retry with backoff | No, hand-written | Yes, configurable |
| Refresh after a write | No | Yes, through invalidation |
Why this is a different kind of state
The root cause is a category difference. State such as a form input or a toggle is owned by the client. You create it, you change it, and nobody else can. Data from an API is server state. It lives on a remote machine, you hold only a snapshot, and it can change without you knowing. Server state needs caching, staleness rules, and synchronization. useState was designed for client state, and useEffect was designed for synchronizing with external systems. Neither was designed to be a cache.
When effect-based fetching is still fine
Not every app needs a library. A hook like useFetch is a reasonable choice when:
- The app has a handful of requests and little data reuse.
- Each piece of data is used by one component.
- Users rarely return to the same screen in one session.
- You cannot add a dependency, or you are building a small demo.
The warning sign is when you start adding a cache object, an event listener for refetching, or a retry loop to your own hook. At that point you are rebuilding a library with fewer tests than the existing ones.
Practice
Exercise
A page shows the same user's name in a header and in a sidebar, and both components call useFetch('/api/me'). Name two problems this causes, and say which missing feature would fix each.
Show answer
First, the browser sends two identical requests, because each hook instance has its own state and effect. Request deduplication would fix this. Second, the two copies can hold different data, and after an update neither knows the other is out of date. A shared cache with invalidation would fix this.
Exercise
Why is passing an inline object such as { headers: { Accept: 'application/json' } } as a dependency of a fetching effect a bug, and how do you avoid it?
Show answer
A new object is created on every render, so React sees a changed dependency each time and re-runs the effect, which can cause a request loop. Depend on primitive values such as the URL, define the object outside the component, or memoize it with useMemo.
Exercise
Why is server state different from client state such as a toggle?
Show answer
Client state is owned by the component and is always current. Server state is a snapshot of data owned by a remote system, so it can become stale without the client knowing. It therefore needs caching, refetching, and invalidation.