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
- Handle HTTP failures explicitly.
- Avoid duplicate requests from accidental re-renders.
- Log network failures with endpoint and context.
Practice
Build a searchable list with pagination, loading/error states, and stale-request protection.