useEffect
Side effects — data fetching, subscriptions, timers, and cleanup
Skills taught: react.useEffect, react.cleanup, react.data-fetching, react.dependency-array
useEffect patterns
// Pattern 1: Run once on mount (empty dependency array)
function DocumentTitle({ title }) {
useEffect(() => {
document.title = title; // side effect: update browser tab title
return () => { document.title = 'App'; }; // cleanup: reset on unmount
}, [title]); // re-run when title changes
return <h1>{title}</h1>;
}
// Pattern 2: Data fetching
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false; // prevent stale state updates if effect re-runs
setLoading(true);
setError(null);
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(res => res.json())
.then(data => { if (!ignore) { setUser(data); setLoading(false); } })
.catch(err => { if (!ignore) { setError(err.message); setLoading(false); } });
return () => { ignore = true; }; // cleanup: ignore response if component re-renders
}, [userId]); // re-run when userId changes
if (loading) return <p>Loading user {userId}...</p>;
if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;
return (
<div>
<h3>{user?.name}</h3>
<p>{user?.email}</p>
</div>
);
}
// Pattern 3: Timer with cleanup
function Stopwatch() {
const [running, setRunning] = useState(false);
const [ms, setMs] = useState(0);
useEffect(() => {
if (!running) return; // don't start if paused
const id = setInterval(() => {
setMs(prev => prev + 10);
}, 10);
return () => clearInterval(id); // CLEANUP: stop the timer
// Without cleanup, the interval keeps running even after component unmounts!
}, [running]); // re-run when running changes
const fmt = (ms) => {
const s = Math.floor(ms / 1000);
const m = String(ms % 1000).padStart(3, '0');
return `${s}.${m}s`;
};
return (
<div style={{ fontFamily: 'monospace', padding: '8px' }}>
<h2 style={{ fontSize: '2rem' }}>{fmt(ms)}</h2>
<div style={{ display: 'flex', gap: '8px' }}>
<button onClick={() => setRunning(r => !r)}>{running ? 'Pause' : 'Start'}</button>
<button onClick={() => { setRunning(false); setMs(0); }}>Reset</button>
</div>
</div>
);
}
function App() {
return <Stopwatch />;
}
Frequently Asked Questions
Why can't I make useEffect's callback async?
useEffect's callback must either return a cleanup function or nothing. An async function returns a Promise — React would receive a Promise as the 'cleanup', which it doesn't know how to call. The fix: define an async function inside the effect and call it: useEffect(() => { async function load() { ... } load(); }, []).