useEffect & Fetching Data
Side effects
Anything that reaches outside rendering is a side effect: fetching data, timers, subscriptions, changing document.title. Run them with useEffect:
useEffect(() => {
// runs after render
return () => { /* cleanup: before re-running or unmounting */ };
}, [dependencies]);
The dependency array
| Array | Effect runs |
|---|---|
| none | after every render (rarely what you want) |
[] | once, after the first render |
[userId] | first render, then whenever userId changes |
Fetching data correctly
Handle loading, error and data, and ignore results that arrive after the component has changed (the cleanup flag):
useEffect(() => {
let ignore = false;
setLoading(true);
fetch(`/api/users/${id}`)
.then((r) => r.json())
.then((data) => { if (!ignore) setUser(data); })
.catch(setError)
.finally(() => { if (!ignore) setLoading(false); });
return () => { ignore = true; };
}, [id]);
Rules of hooks
- Call hooks at the top level of a component, never inside
ifstatements or loops. - Only call hooks from React components or custom hooks (
useSomething).
💡 For real apps, data libraries such as TanStack Query (or a framework's loaders) handle caching, retries and loading states for you.
Example
import { useEffect, useState } from "react";
export default function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => {
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
})
.then((data) => { if (!ignore) setUsers(data); })
.catch((err) => { if (!ignore) setError(err.message); })
.finally(() => { if (!ignore) setLoading(false); });
return () => { ignore = true; }; // cleanup
}, []);
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;
return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}
// 💻 Run in a Vite + React project