Why useEffect Fires Twice in React

🚨 Why is useEffect firing twice in React? (Every React developer hits this at least once 👀) You write a simple useEffect(): useEffect(() => { console.log("API Called"); }, []); Expected: ✅ Runs once when component mounts Reality in development: ❌ Runs twice At first, it feels like a bug. But it’s actually React helping you. Here’s why: In React 18, Strict Mode intentionally runs effects twice in development to detect: • Side effects that aren’t properly cleaned up • Unsafe component behavior • Bugs that may appear in production later Think of it like a stress test for your code. Example: Without cleanup: API calls may duplicate Event listeners may stack Timers may keep running Better approach: ✔ Add cleanup functions ✔ Make effects idempotent ✔ Avoid unnecessary side effects Example: useEffect(() => { const timer = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(timer); }, []); Important: This double execution happens only in development mode, not production. So next time useEffect fires twice, don’t panic. React is exposing hidden issues before users do. 📌 Part 1 of my React series Next: Dependency Array Explained Simply ⚛️ https://inhamtools.com/ https://lnkd.in/daSAPzAX #ReactJS #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories