Forms and Data

Working with APIs in React

Fetch, display, and mutate backend data while handling loading, error, and success states.

Fetch data with useEffect

tsx
const [users, setUsers] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
  fetch('/api/users')
    .then(r => r.json())
    .then(data => setUsers(data))
    .catch(err => setError(String(err)))
    .finally(() => setLoading(false));
}, []);

Manage async states

  • Loading
  • Error
  • Empty
  • Success

Production recommendation

Use TanStack Query for:

  • Response caching
  • Background refetching
  • Retries and stale-time control
  • Mutation handling

Next, we will manage shared state.