useEffect lets you run side effects — API calls, subscriptions,
timers, and DOM manipulation that happens outside React's render cycle.
Basic useEffect
JSX
import { useState, useEffect } from 'react';
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => {
setTime(new Date());
}, 1000);
// Cleanup function — runs when component unmounts
return () => clearInterval(timer);
}, []); // Empty array = run once on mount
return <p>{time.toLocaleTimeString()}</p>;
}Fetching data
JSX
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
setError(null);
fetch(`/api/users/${userId}`)
.then(res => {
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
})
.then(data => setUser(data))
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, [userId]); // Re-run when userId changes
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
if (!user) return null;
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}Dependency array rules
JSX
// Run once on mount
useEffect(() => { ... }, []);
// Run when count changes
useEffect(() => { ... }, [count]);
// Run on every render (avoid!)
useEffect(() => { ... });Always include all reactive values in the dependency array. Missing dependencies cause stale closures — the effect uses old values.
Cleanup
JSX
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = connect(roomId);
return () => {
connection.disconnect(); // Cleanup on unmount or roomId change
};
}, [roomId]);
}Tips
- Keep effects focused — one effect, one concern.
- Always clean up timers, subscriptions, and connections.
- For complex data fetching, consider React Query or SWR.
- If you can compute it from state/props, don't put it in an effect.
🎉 You have completed the React course! You now know JSX, components, props, state, events, lists, forms, and effects — the core skills for building modern web applications.