Skip to content

Loading Again When Props Change

The Course
•
15 min study

TopicDetails loads one topic, chosen by its id prop. Because id is in the dependency list, choosing another topic loads that one. This effect waits with .then rather than await: it has one step and no error handling, so it doesn't need an async function. It means the same as the previous lesson's await version.

JavaScript
useEffect(() => {
  setTopic(null);
  fetchTopic(id).then((data) => {
    setTopic(data);
  });
}, [id]);
Details for the chosen topic React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so these functions wait, // like a real request would, and then return data or fail. const topics = [ { id: 1, title: "Components", summary: "Functions that return JSX." }, { id: 2, title: "State", summary: "A component's memory between renders." }, { id: 3, title: "Effects", summary: "Code that keeps something outside React in step." }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopics({ fail = false } = {}) { await wait(600); if (fail) throw new Error("The server didn't answer. Try again."); return topics.map(({ id, title }) => ({ id, title })); } // Topic 1 answers slowly and topic 3 quickly, like a real server sometimes does. export async function fetchTopic(id) { await wait(id === 1 ? 1200 : id === 2 ? 600 : 200); const topic = topics.find((t) => t.id === id); if (!topic) throw new Error(`No topic with id ${id}.`); return topic; } import { useState } from "react"; import TopicDetails from "./TopicDetails.jsx"; const choices = [ { id: 1, title: "Components" }, { id: 2, title: "State" }, { id: 3, title: "Effects" }, ]; export default function App() { const [selectedId, setSelectedId] = useState(2); return ( <main> <h1>Topic details</h1> {choices.map((choice) => ( <button key={choice.id} onClick={() => setSelectedId(choice.id)} disabled={choice.id === selectedId}> {choice.title} </button> ))} <TopicDetails id={selectedId} /> </main> ); } import { useEffect, useState } from "react"; import { fetchTopic } from "./api.js"; export default function TopicDetails({ id }) { const [topic, setTopic] = useState(null); useEffect(() => { setTopic(null); fetchTopic(id).then((data) => { setTopic(data); }); }, [id]); if (topic === null) return <p className="muted">Loading…</p>; return ( <section className="card"> <h2>{topic.title}</h2> <p>{topic.summary}</p> </section> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

The pretend server answers at different speeds: Components takes 1.2 seconds, State 0.6 and Effects 0.2. Real servers vary like this too.

Predict: two quick clicks

Click Components, then Effects straight away, before Components has finished loading. Which topic is highlighted, and which details do you see after a couple of seconds?

Check your prediction

The Effects button is selected, but after a moment the card shows Components. Both requests were running. Effects answered first and was shown, then the slow Components answer arrived and replaced it. The page now disagrees with itself.

This is called a race condition: the result depends on which request wins the race. You can't control how fast a server answers, so the component has to ignore answers it no longer wants.

Ignore stale answers with cleanup

JavaScript
useEffect(() => {
  let ignore = false;
  setTopic(null);
  fetchTopic(id).then((data) => {
    if (!ignore) setTopic(data);
  });
  return () => {
    ignore = true;
  };
}, [id]);

Each run of the effect has its own ignore variable. When id changes, React runs the old effect's cleanup first, which sets that run's ignore to true. Its answer may still arrive, but it's dropped. Only the latest request can update the page.

Make the change in TopicDetails.jsx and repeat the two quick clicks. The details now always match the highlighted button.

The same idea everywhere

This is the pattern the last lesson was missing too. Add let ignore and a cleanup to any effect that loads data, even when a race seems unlikely. On your own computer, StrictMode's double run of effects relies on the cleanup in the same way.

On real projects, libraries such as TanStack Query handle loading, caching and races for you. Knowing the pattern underneath tells you what those libraries are doing.

Exercise

Why not just check the id?

Someone suggests a different fix: inside .then, compare data.id with id and only call setTopic if they match. Does that work? Explain using what each render's id is.

Hint 1: the idea

A callback keeps the values of the render that created it. Comparing two values from the same old request cannot tell you which request is current.

Hint 2: a first step

Which id does the .then callback see: the one from when the request started, or the latest one?

Show one solution

It doesn't work. The callback belongs to the render that started the request, so its id is that render's id, and the slow answer always matches it. data.id === id is true for the stale answer too. Only something the newer render can change, such as the cleanup setting ignore, can tell the old request that it's out of date.

Was this article helpful?

Your response is saved on this device.