React ยท Chapter 30 of 42

Data Fetching

React components often need to fetch data from an API. The most common pattern combines `useEffect` (to trigger the fetch) with `useState` (to store the result, loading, and error status).

Modern apps increasingly use libraries like React Query or SWR to handle caching, retries, and background refetching automatically.

Basic fetch pattern

Call `fetch()` inside `useEffect`, update state with the result, and handle errors with try/catch or `.catch()`.

Data fetching libraries

Libraries like React Query and SWR handle caching, deduplication, and refetching, reducing manual boilerplate significantly.

Example 1 (jsx)
import { useState, useEffect } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("/api/users")
      .then(res => res.json())
      .then(setUsers);
  }, []);

  return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
Output
(renders a list of users fetched from the API)

The effect fetches data once on mount and stores it in state.

Key points

  • Combine useEffect and useState for basic data fetching.
  • Always handle both loading and error states.
  • Fetch typically runs inside useEffect with an empty dependency array.
  • Libraries like React Query/SWR simplify caching and refetching.
๐Ÿ’ก Note: Remember to guard against setting state on an unmounted component (via cleanup or an abort controller).

๐Ÿ“ Quick Quiz

1. Which two hooks are commonly combined for data fetching?

2. What library helps simplify data fetching and caching?

3. What should you handle besides the successful data response?