βοΈ
EPISODE 02
side effects Β· cleanup Β· dependencies Β· data fetching
useEffect
Run side effects (data fetches, subscriptions, timers) outside the render cycle. Learn the dependency array, cleanup, and how to fetch data correctly.
useEffectside effectcleanupdependencies
Duration
β± About 2 hours
Level
π Intermediate
Prerequisite
π― react-01
OUTCOME
Fetch and subscribe to data with proper cleanup
What you'll learn
- 1Use useEffect with the right dependency array
- 2Return a cleanup function for subscriptions
- 3Fetch data in an effect (or prefer Suspense / server components)
- 4Avoid effect anti-patterns
1. Basic Effect
tsx
useEffect(() => {
document.title = `${count} clicks`;
}, [count]); // runs after every render where count changed- Empty deps [] β runs once on mount
- No deps β runs after every render (rarely what you want)
- Deps [a, b] β runs when a or b changes
2. Cleanup
tsx
useEffect(() => {
const id = setInterval(() => console.log("tick"), 1000);
return () => clearInterval(id); // cleanup on unmount/dep change
}, []);Cleanup runs before the next effect fires and on unmount β essential for timers and subscriptions.
3. Data Fetching
tsx
function Users() {
const [users, setUsers] = useState<User[] | null>(null);
useEffect(() => {
const controller = new AbortController();
(async () => {
const res = await fetch("/api/users", { signal: controller.signal });
const data = await res.json();
setUsers(data);
})().catch(err => { if (err.name !== "AbortError") console.error(err); });
return () => controller.abort();
}, []);
if (!users) return <p>Loading...</p>;
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}4. Anti-patterns
- Setting state in an effect that immediately re-triggers itself (infinite loop)
- Forgetting deps and using stale state
- Using an effect to derive state β derive in render instead
- Subscribing without cleanup
π‘
Many "do I need an effect?" answers are no. Read the React docs page "You Might Not Need an Effect".
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β