More Hooks
useEffect
useEffect runs code after the component renders. Use it to sync with things outside React: fetching data, timers, subscriptions.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((r) => r.json())
.then((data) => setUsers(data))
.finally(() => setLoading(false));
}, []); // [] = run once, after the first render
if (loading) return <p>Loading...</p>;
return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}| Dependency array | Effect runs |
|---|---|
[] | Once, after the first render |
[userId] | After the first render and whenever userId changes |
| (none) | After every render (rarely what you want) |
Cleaning up
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id); // runs when the component is removed
}, []);