All articles

⚛️ React useEffect — How Does It Work?

For example, fetching data, setting up timers, or listening for browser events.

⚛️ React useEffect — How Does It Work?

ᅠ 📘 Engineering Notes | From Concepts to Code — Post 14 ᅠ When building React applications, we often need to perform operations outside the normal rendering process.

For example, fetching data, setting up timers, or listening for browser events.

That's where useEffect comes in! 🚀

Let's understand it with simple examples. 👇 ᅠ 1️⃣ What Is useEffect? 🔄

useEffect is a React Hook that helps synchronize a component with external systems.

It runs after React commits updates to the UI.

Example:

useEffect(() => { document.title = "My React App"; }, []);

This updates the browser tab title when the component mounts. ᅠ 2️⃣ Understanding the Dependency Array 📦

The dependency array controls when the Effect needs to run again.

🔹 No dependency array Runs after every committed render.

🔹 Empty array [] Runs on mount, with an extra development check possible in Strict Mode.

🔹 [userId] Runs on mount and when userId changes. ᅠ 3️⃣ Real-World Example — Timer ⏱️

Imagine displaying a timer in a dashboard.

useEffect(() => { const timer = setInterval(() => { console.log("Tick"); }, 1000);

return () => clearInterval(timer); }, []);

The Effect starts a timer, and the cleanup function clears it when needed. ᅠ 4️⃣ Why Is Cleanup Important? 🧹

Effects may set up subscriptions, timers, or event listeners.

Without proper cleanup, these can continue running unnecessarily.

✅ Clear timers ✅ Remove event listeners ✅ Disconnect subscriptions ✅ Cancel or ignore outdated requests ᅠ 5️⃣ Common useEffect Mistakes ⚠️

❌ Missing required dependencies ❌ Forgetting cleanup ❌ Using Effects for simple calculations ❌ Creating unnecessary update loops

💡 If a value can be calculated directly from props or state during rendering, you often don't need useEffect. ᅠ 💡 My Key Takeaway

useEffect isn't just a way to run code after rendering.

Its main purpose is to synchronize React components with external systems.

Understanding dependencies and cleanup helps us build more predictable and maintainable applications.

🚀 Use Effects when needed, not for everything. ᅠ 💬 What's the most common useEffect mistake you've encountered in React? ᅠ #ReactJS #ReactHooks #SoftwareEngineering #FrontendDevelopment #JavaScript