Fetching Data from an API
Real apps load data from a server. In React, start the request in useEffect, keep the result in state, and show loading and error messages.
Almost every real React app shows data from a server: products, messages, search results. Getting data takes time and can fail, so a good component always handles three situations: loading (show a spinner or skeleton), error (show a friendly message and a retry), and success (show the data). Users notice when apps skip the first two - a blank screen or a silent failure feels broken.
Example
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
const { useState, useEffect } = React;
function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
let cancelled = false;
async function load() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
if (!res.ok) throw new Error("Status " + res.status);
const data = await res.json();
if (!cancelled) setUsers(data);
} catch (e) {
if (!cancelled) setError(e.message);
} finally {
if (!cancelled) setLoading(false);
}
}
load();
return () => { cancelled = true; }; // stop if the component goes away
}, []); // [] = run once, when it first shows
if (loading) return <p>Loading...</p>;
if (error) return <p style={{ color: "red" }}>Could not load: {error}</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name} - {u.address.city}</li>)}
</ul>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfSearch that reloads
Put a value in the dependency array and the effect runs again whenever it changes:
Example
useEffect(() => {
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(r => r.json())
.then(setResults);
}, [query]); // runs again each time query changesIn bigger apps, libraries such as TanStack Query handle loading, caching and retrying for you. Learn the plain way first so you understand what they do.
Key points
- Start requests in useEffect and keep results in state.
- Always handle loading and error states.
- Put inputs like the search text in the dependency array.
- Libraries like TanStack Query add caching and retries.
📝 Test yourself
1. Where should you start a fetch when a component first shows?
2. What does the empty array in useEffect(fn, []) mean?
3. Fill in what useEffect returns to clean up:
return () => { cancelled = ; };
