You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Not everything in a React app is pure rendering. You often need to fetch data from APIs, set up subscriptions, or interact with browser APIs. The useEffect hook lets you synchronise your component with these side effects. This lesson covers useEffect, fetching data, loading/error states, cleanup, custom hooks, and an overview of SWR and React Query.
A side effect is anything that reaches outside the component's rendering logic:
| Side Effect | Example |
|---|---|
| Fetching data | Calling an API on mount |
| Subscriptions | WebSocket connections, event listeners |
| Timers | setTimeout, setInterval |
| DOM manipulation | Focusing an input, measuring layout |
| Logging / analytics | Tracking page views |
import { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
// Cleanup function — runs when the component unmounts
return () => clearInterval(interval);
}, []); // Empty dependency array = run once on mount
return <p>Elapsed: {seconds}s</p>;
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.