← Back to React, page 4

react-0074 · Medium mid

Write a useFetch hook that handles loading and error states and cancels outdated requests when the URL changes or the component unmounts.

Keep data, error and loading state in the hook. In an effect that depends on the url, create an AbortController, pass its signal to fetch, and return a cleanup function that calls abort(). Ignore the AbortError in the catch block. The abort stops the old request from updating state, so a slow response for an old URL cannot overwrite a newer one. Accept the fetcher as an argument to make the hook testable.

Full answer

Without cancellation, a hook has a race condition. If the url changes from A to B and A is slower, A's response arrives last and the screen shows the wrong data.

The fix is in the effect. Each run creates its own AbortController. Its signal goes to fetch(url, { signal }). The cleanup function calls controller.abort(). React runs the cleanup before the next effect and on unmount, so an old request is aborted as soon as it is outdated. An aborted fetch rejects with an error named AbortError, which is not a real failure, so the catch block ignores it.

State handling: reset to a loading state when the url changes. Check response.ok, because fetch does not reject on 404 or 500 statuses. Parse JSON after that and set data.

A useful trick for testing and reuse is to accept the fetcher with a default: useFetch(url, fetcher = fetch). In tests or demos a fake can be passed in.

The abort pattern is still needed even when you use a flag such as let ignore = false in cleanup. The flag prevents stale state updates, and the abort also saves bandwidth and server work, and stops downloading bodies nobody wants.

In production, a library such as TanStack Query usually replaces this hook, adding caching, retries and deduplication. In interviews, writing the hook shows you understand effects, cleanup and races. The example uses a fake fetch where course 1 is slower than course 2, to prove that the older response is discarded.

jsx
import { useEffect, useState } from 'react';

function useFetch(url, fetcher = fetch) {
  const [state, setState] = useState({ data: null, error: null, loading: true });

  useEffect(() => {
    const controller = new AbortController();
    setState({ data: null, error: null, loading: true });

    fetcher(url, { signal: controller.signal })
      .then((response) => {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.json();
      })
      .then((data) => setState({ data, error: null, loading: false }))
      .catch((error) => {
        if (error.name === 'AbortError') return;
        setState({ data: null, error, loading: false });
      });

    return () => controller.abort();
  }, [url, fetcher]);

  return state;
}

function fakeFetch(url, { signal }) {
  const delay = url.endsWith('1') ? 80 : 10;
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve({ ok: true, json: async () => ({ title: 'Data for ' + url }) }), delay);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      console.log('aborted ' + url);
      reject(new DOMException('Aborted', 'AbortError'));
    });
  });
}

export default function App() {
  const [id, setId] = useState(0);
  const { data, error, loading } = useFetch('/courses/' + id, fakeFetch);

  return (
    <div>
      <button onClick={() => setId(1)}>Course 1</button>
      <button onClick={() => setId(2)}>Course 2</button>
      <p>{loading ? 'Loading...' : error ? error.message : data.title}</p>
    </div>
  );
}

The check clicked Course 1 (the slow one) and then Course 2 straight away. The requests for course 0 (the initial one) and course 1 were aborted, and only course 2 updated the screen. The final abort line is the unmount cleanup calling abort on a request that had already finished, which does nothing. Output of the run: aborted /courses/0 aborted /courses/1 after both requests settled: Data for /courses/2 aborted /courses/2

Key points

  • Create an AbortController per effect run and abort in the cleanup.
  • Ignore AbortError. Treat other failures as errors.
  • Check response.ok because fetch does not reject on HTTP errors.
  • Reset loading state when the url changes.
  • Prefer a data library in production, but know this pattern.

Common mistakes

  • Not aborting or ignoring old responses, so a slow old request overwrites new data.
  • Treating AbortError as a user-visible error.
  • Forgetting response.ok and treating a 404 page as success.
  • Passing an inline fetcher function in the dependency array, which restarts the effect on every render.
  • Calling setState after unmount without protection in code that cannot abort.

Follow-ups

  • What other approach prevents stale updates besides aborting?
  • Why can the hook not be an async function passed to useEffect?
  • How would you add retries or caching, and why might you use TanStack Query instead?

Tips

  • Describe the race first, then the fix. It shows you know why.
  • Mention response.ok. Many candidates forget it.
  • Say a data library is the production answer.