useEffect() is used to handle side effects in React functional components — things that happen outside the normal render process.
✅ Common Scenarios to Use useEffect()
1️⃣ Fetching Data from an API
When you need to load data after a component mounts or when a value changes.
useEffect(() => {
fetch("/api/users")
.then(res => res.json())
.then(setUsers);
}, []);
✔ Runs once on mount
✔ Prevents repeated calls
2️⃣ Subscribing to Events or WebSockets
Set up listeners and clean them up properly.
useEffect(() => {
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
✔ Avoids memory leaks
3️⃣ Using Timers (setTimeout, setInterval)
useEffect(() => {
const timer = setInterval(() => {
console.log("tick");
}, 1000);
return () => clearInterval(timer);
}, []);
4️⃣ Syncing State with Props
When state must update based on prop changes.
useEffect(() => {
setFormData(user);
}, [user]);
5️⃣ Updating the DOM Manually
When you need direct DOM access.
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
6️⃣ Calling APIs on Dependency Change
useEffect(() => {
fetchData(query);
}, [query]);
✔ Runs only when query changes
7️⃣ Cleanup on Component Unmount
Releasing resources.
useEffect(() => {
return () => {
console.log("Component unmounted");
};
}, []);
❌ When NOT to Use useEffect()
- ❌ For simple derived values
- ❌ For pure calculations
- ❌ When state can be computed during render
// ❌ Avoid
useEffect(() => {
setFullName(first + " " + last);
}, [first, last]);
✔ Instead:
const fullName = first + " " + last;
🧠 Key Rule
If something does not interact with the outside world, it usually does not belong in
useEffect().
🎯 Short Interview Answer
useEffect()is used for side effects such as data fetching, subscriptions, timers, DOM updates, and syncing state with external systems.
It runs after rendering and supports cleanup logic, making it ideal for managing component lifecycle behavior in functional components.
⭐ One-Line Summary
Use useEffect() whenever React needs to interact with something outside the render cycle.