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.
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>;
}(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.
