React Component That Fetches a List Safely When Its Endpoint Changes
System DesignModel answerLast updated
Build a React component that fetches a list from a prop-supplied URL inside useEffect, with correct loading, empty, error and success states and no stale-response bugs.
Write a React function component, ItemList, that takes a single prop, endpoint (a URL string), and uses useEffect to fetch and render the list found there.
Data contract
- A successful response is a JSON array of objects shaped like
{ id: string, label: string }. - Every
idin a valid response is unique.
Required behavior
- Show a loading indicator while a request is pending.
- Show an empty message when the request succeeds but the array has no items.
- Show the items (their labels) when the request succeeds and the array has items.
- Show an error message when the request fails, including network failures, non-2xx HTTP statuses, and bodies that do not match the contract.
- If
endpointchanges while an earlier request is still in flight, the earlier response must never overwrite the state belonging to the newer endpoint. - Unmounting the component must not trigger state updates or leave work running.
What to discuss alongside the code
- Who should own fetching and caching: the component or a shared layer?
- What should the UI show while switching between endpoints?
- Can the request be canceled, and what happens on unmount?
- How would you add a retry button?
Hints
Hint 1
Which values does the effect read from the component? Those belong in the dependency array, and the effect should re-run when they change.
Hint 2
Return a cleanup function from the effect. Think about two tools: one that cancels the network request, and one that makes a late response harmless even if cancellation does not stop it.
Hint 3
Do not trust the response body. Check the HTTP status, then check that the JSON is an array of well-formed items before rendering, and decide which state each outcome maps to. Also think about which value is a stable React key.
Hint 4
Reset to the loading state at the start of each effect run so you never show the old endpoint's items under the new endpoint's heading.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the component as a small state machine with four states: loading, empty, success, error. The effect owns one request per endpoint value. Its cleanup invalidates that request, so only the latest request can ever write state.
Keep status, items and error message together in one state object. That avoids impossible combinations such as "loading" with an error message still set, and it lets each transition be a single atomic setState.
Implementation
import { useEffect, useState } from "react";
function parseItems(data) {
if (!Array.isArray(data)) throw new Error("Response is not an array");
const seen = new Set();
for (const item of data) {
if (
item === null ||
typeof item !== "object" ||
typeof item.id !== "string" ||
typeof item.label !== "string"
) {
throw new Error("Malformed item in response");
}
if (seen.has(item.id)) throw new Error("Duplicate id: " + item.id);
seen.add(item.id);
}
return data;
}
export function ItemList({ endpoint }) {
const [state, setState] = useState({
status: "loading",
items: [],
error: null,
});
useEffect(() => {
const controller = new AbortController();
let ignore = false;
setState({ status: "loading", items: [], error: null });
(async () => {
try {
const res = await fetch(endpoint, { signal: controller.signal });
if (!res.ok) throw new Error("HTTP " + res.status);
const items = parseItems(await res.json());
if (ignore) return;
setState({
status: items.length === 0 ? "empty" : "success",
items,
error: null,
});
} catch (err) {
if (ignore || err.name === "AbortError") return;
setState({ status: "error", items: [], error: err.message });
}
})();
return () => {
ignore = true;
controller.abort();
};
}, [endpoint]);
if (state.status === "loading") return <p>Loading...</p>;
if (state.status === "error") return <p role="alert">Could not load: {state.error}</p>;
if (state.status === "empty") return <p>No items found.</p>;
return (
<ul>
{state.items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
);
}
Why this works
Dependency array. The effect reads only endpoint, so [endpoint] is correct. Omitting it would fetch once and go stale. Adding unstable values such as inline objects would refetch on every render.
Cleanup does two jobs.
controller.abort()cancels the in-flight request, saving bandwidth and rejecting the promise with anAbortError.- The
ignoreflag is a second line of defense. Some code paths (for example a response already received and being parsed, or a mockedfetchthat ignores signals) can still resolve after cleanup. The flag guarantees a stale result is dropped.
When endpoint changes, React runs the old cleanup before the new effect. Request A is therefore invalidated before request B starts, so A can never overwrite B even if A responds later.
Reset on change. Setting loading at the start of the effect prevents the previous endpoint's items from appearing under the new one. An alternative is to keep showing old data with a subtle "refreshing" indicator, but that is a product decision and should be explicit.
Error handling covers three layers.
- Network failure:
fetchrejects. - HTTP failure:
fetchdoes not reject on 404 or 500, sores.okmust be checked. - Shape failure: invalid JSON (
res.json()throws) or a body that violates the contract, caught byparseItems.
AbortError is deliberately not treated as a failure, because it is the expected result of cleanup.
Keys. Use item.id, not the array index. IDs are unique per the contract, and stable keys let React preserve and reorder DOM nodes correctly. Validating uniqueness up front turns a silent rendering bug into a visible error state.
Empty versus success. An empty array is a valid response and deserves its own message rather than a blank screen or an error.
Unmount. Cleanup runs on unmount too, so the request is aborted and no state update is attempted afterward. In React StrictMode development builds, effects run, clean up and run again; this design handles that because each run is self-contained.
Trade-offs and discussion points
- Ownership of fetching. For a single screen, a local effect is fine. In a real app, a data layer such as React Query or SWR gives caching, deduplication, retries, background refresh and built-in race handling. The effect version is what you write when you need to show you understand what those libraries do.
- Caching. Without a cache, switching A to B to A refetches A. A simple
Mapkeyed by endpoint outside the component, or a data library, fixes that, at the cost of invalidation logic. - Retry. Add a
retryCountstate to the dependency array and increment it from a button. The effect re-runs with the same cleanup guarantees. For automatic retries, use bounded exponential backoff and only for network errors or 5xx responses, never for 4xx. - Timeouts.
fetchhas no default timeout. UseAbortSignal.timeout(ms)or a timer callingcontroller.abort(), and map it to an error message distinct from cleanup aborts. - Large lists. Beyond a few thousand rows, add pagination or virtualization.
- Accessibility. Use
role="alert"for errors andaria-busyor a status role for loading.
Common mistakes
- Leaving out
endpointfrom the dependency array, or using an empty array. - Making the effect callback itself
async(it would return a promise instead of a cleanup function). - Relying only on
ignoreor only onAbortControllerwithout understanding what each covers. - Forgetting
res.ok, so a 500 with a JSON error body is rendered as data. - Using the array index as a key.
- Not resetting state on endpoint change, so old data flashes under the new endpoint.
- Treating
AbortErroras a user-facing failure. - Updating state after unmount.