Why useEffect runs twice in React Strict Mode

⚛️ React Interview Question — Why does useEffect run twice in React Strict Mode? If you've ever seen your API call firing twice in development, you're not alone. This is one of the most common questions asked in React interviews. useEffect(() => { console.log("Fetching data..."); fetchUsers(); }, []); 🧠 Question: Why does this useEffect run twice in development but only once in production? ✅ The Answer In React Strict Mode, React intentionally runs certain lifecycle functions twice in development to help detect: Side effects Memory leaks Unsafe operations Non-idempotent code This behavior happens only in development, not in production builds. Real-world scenario You may notice: Duplicate API calls Double console logs Repeated state updates This is not a bug — it's a debugging mechanism built into React. Best Practice Always write useEffect logic that is: ✅ Safe to run multiple times ✅ Cleaned up properly ✅ Free from unintended side effects Example with cleanup: useEffect(() => { const controller = new AbortController(); fetch("/api/users", { signal: controller.signal, }); return () => { controller.abort(); }; }, []); 💡 My learning lesson: When debugging React behavior, always check whether Strict Mode is enabled before assuming there is a bug. This small detail can save hours during development and interviews. #FrontendDeveloper #ReactJS #JavaScript #WebDevelopment #FrontendInterview #ReactDeveloper #Coding #TechLearning #hiring

To view or add a comment, sign in

Explore content categories