AceDevHub
Intermediate React Interview QuestionsIntermediateScenario

React · Question 70

A component fetches data when an ID changes, but a slower old request sometimes overwrites the result of a newer request. How would you fix it?

Direct answer

Make the Effect cleanup invalidate or cancel work from the previous ID so an obsolete request cannot commit stale data after the component has synchronized to a newer ID.

UserProfile.jsx
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    async function load() {
      try {
        const response = await fetch(
          `/api/users/${userId}`,
          { signal: controller.signal }
        );
        const data = await response.json();
        setUser(data);
      } catch (error) {
        if (error.name !== "AbortError") {
          throw error;
        }
      }
    }

    load();
    return () => controller.abort();
  }, [userId]);

  return <Profile user={user} />;
}

When userId changes, cleanup aborts the previous request before the Effect starts synchronization for the new ID. Another valid pattern is to mark the old request as ignored if the underlying API cannot be cancelled.