Data Fetching and Effects

Side effects should be controlled and observable. Fetching logic must handle loading, success, and failure paths.

useEffect basics

useEffect(() => {
  let canceled = false;
  fetch("/api/items")
    .then(r => r.json())
    .then(data => { if (!canceled) setItems(data); });
  return () => { canceled = true; };
}, []);

Async state model

Use explicit states: idle, loading, success, and error.

Cancellation and stale data

Prevent state updates from stale requests when component lifecycle changes.

Separation of concerns

Move network behavior into hooks or service modules as integration complexity grows.

Professional tips

  1. Handle HTTP failures explicitly.
  2. Avoid duplicate requests from accidental re-renders.
  3. Log network failures with endpoint and context.

Practice

Build a searchable list with pagination, loading/error states, and stale-request protection.