← React Beginner Questions - Set 2 Q14
React Beginner Questions - Set 2
For everything that must happen outside rendering: fetching, subscriptions, timers. The cleanup function is the half people forget.
import { useEffect, useState } from 'react';
export default function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(r => (r.ok ? r.json() : Promise.reject(r.status)))
.then(setUser)
.catch(err => {
if (err.name !== 'AbortError') setError(String(err));
});
return () => controller.abort(); // runs before the next effect
}, [userId]); // re-run only when userId changes
if (error) return <p>Error: {error}</p>;
if (!user) return <p>Loading…</p>;
return <h2>{user.name}</h2>;
}