useEffect — Complete Guide
useEffect — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.
On this page
React.js Tutorial · Lesson 24 of 100
useEffect
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Learn by example · ~6 min · Module 3: Forms & Hooks
What is this?
useEffect runs side effects after render — fetching data, subscribing to events, or syncing with document title. You can return a cleanup function.
Why should you care?
Data fetching and subscriptions do not belong inside render. useEffect separates "what to show" from "what to do after paint."
See it live — copy this example
Paste into src/App.jsx (or the file noted in the steps). Save and watch the browser update.
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(r => r.json())
.then(setUser);
}, [userId]);
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
Run Example »
Edit the code and click Run to see the result update live.
What happened?
- The [userId] dependency array means: run again when userId changes.
- Empty [] means run once on mount.
Try it yourself
- Fetch data in useEffect with a dependency array.
- Add cleanup: return () => clearInterval(id) for timers.
- Do not omit deps if you use props/state inside the effect.
- Change text or labels in the example and save — watch the browser update.
- Break the code on purpose (remove a bracket), read the error message, then fix it.
Remember
useEffect(fn, deps) for side effects after render. Include dependencies you use inside the effect. Return cleanup when needed.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!