1. Concept library
  2. Web Dev with React
  3. Module 5: Effects and data fetching

Concept

Fetching data in components

Fetching in an effect means handling loading, error and success states, ignoring responses that arrive after the component changed its mind, and cancelling when it unmounts. A small hook or a data library hides this once.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Name the states a fetch in a component has to handle
  2. Write a fetch effect that ignores responses from an earlier render
  3. Spot the race where a slow earlier response overwrites newer data

In practice

A few lines that show Fetching data in components doing its job.

TSX
useEffect(() => {
  const controller = new AbortController();
  setState({ status: "loading" });
  fetch("/api/users/" + id, { signal: controller.signal })
    .then((r) => r.ok ? r.json() : Promise.reject(new Error("HTTP " + r.status)))
    .then((user) => setState({ status: "ready", user }))
    .catch((error) => {
      if (error.name !== "AbortError") setState({ status: "error", error });
    });
  return () => controller.abort();
}, [id]);

The common mistake

Watch for

Ignoring race conditions. When id changes quickly, an earlier slower response can land last and overwrite the newer data. Abort or flag the stale request in cleanup.

What to know first

Your roadmap puts these before Fetching data in components, unless you already know them.

How it stays learned

Once a session shows you understand Fetching data in components, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Fetching data in components.

Previous in the module← StrictMode double effects