KatInterview

React Component That Fetches a List Safely When Its Endpoint Changes

System DesignModel answer
MediumModel answerSystem DesignreactuseEffectrace-conditions

Last 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 id in a valid response is unique.

Required behavior

  1. Show a loading indicator while a request is pending.
  2. Show an empty message when the request succeeds but the array has no items.
  3. Show the items (their labels) when the request succeeds and the array has items.
  4. Show an error message when the request fails, including network failures, non-2xx HTTP statuses, and bodies that do not match the contract.
  5. If endpoint changes while an earlier request is still in flight, the earlier response must never overwrite the state belonging to the newer endpoint.
  6. 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.