Data Fetching and Effects

Side effects must be synchronized carefully with component lifecycles. Fetching logic should always handle loading, success, failure, and cancellation paths.

useEffect basics

Rendering in React must remain pure, so network requests, subscriptions, and timers belong in useEffect (or an event handler when triggered by a user action). The dependency array tells React when to re-run the effect: an empty array [] runs once after mount, while listing values like [query] re-runs whenever query changes. Every effect that starts an async operation should return a cleanup function:

import { useEffect, useState } from "react";

function UserDirectory({ query }) {
  const [items, setItems] = useState([]);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const controller = new AbortController();
    setIsLoading(true);
    setError(null);

    fetch(`/api/users?q=${encodeURIComponent(query)}`, { signal: controller.signal })
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(data => {
        setItems(data);
        setIsLoading(false);
      })
      .catch(err => {
        // Ignore aborts triggered by unmount or a newer query
        if (err.name === "AbortError") return;
        setError(err.message);
        setIsLoading(false);
      });

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

  if (isLoading) return <p>Loading users...</p>;
  if (error) return <p role="alert">Failed to load: {error}</p>;
  return <ul>{items.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

Async state model

Model asynchronous requests with explicit states—idle, loading, success, and error—rather than assuming data is either present or loading. Notice in the example above that fetch() only rejects on network errors, not on HTTP 404 or 500 responses; checking res.ok ensures server errors transition into the error state instead of parsing an error page as JSON.

Cancellation and stale data

When a user types quickly into a search box, an earlier slow request can resolve after a newer fast request, overwriting fresh results with stale data (a race condition). Passing an AbortController signal—or tracking a canceled boolean in the cleanup function—guarantees that superseded requests never commit stale state.

Separation of concerns

Avoid scattering raw fetch URLs and response-mapping logic across UI components. Extract transport calls into a dedicated API module and wrap reusable loading/error/cancellation logic inside a custom hook (such as useUsers(query)), or adopt a dedicated server-state library when caching, background revalidation, and deduplication are needed.

Professional tips

Keep network integrations predictable in production:

  1. Check response.ok and handle non-2xx HTTP statuses explicitly.
  2. Always include all reactive values read inside useEffect in its dependency array so effects never read stale closures.
  3. Log failed requests with endpoint and status context to speed up incident diagnosis.

Practice

Build a searchable list that fetches results from an API on query change, handles loading, empty, and HTTP error states, and cancels in-flight requests with AbortController.