🚨 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
Why useEffect Fires Twice in React
More Relevant Posts
-
🚀 Crack the Code: The React Lifecycle (Core Level) Ever wondered how React actually manages the life of a component? Whether you’re prepping for a Senior Dev interview or just trying to squash that persistent memory leak, mastering the Lifecycle Phases is your secret weapon. 🛠️ React components are like living organisms: they are born, they grow, and they eventually pass away. 1️⃣ The Birth: Mounting Phase This is where it all begins. React initializes state and builds the initial Virtual DOM. The Hook: useEffect(() => { ... }, []) Pro Tip: Use this phase for initial API calls or setting up subscriptions. If you leave the dependency array empty, it runs exactly once—like a birth certificate! 2️⃣ The Growth: Updating Phase Whenever props or state change, React springs into action. This is where the magic of Diffing happens—React compares the old Virtual DOM with the new one to update only what’s necessary. The Hook: useEffect(() => { ... }, [dependency]) Pro Tip: Always be intentional with your dependency array. Missing a dependency can lead to stale data; adding too many can cause infinite loops! 🔄 3️⃣ The End: Unmounting Phase The most ignored phase, but arguably the most critical for performance. 🧹 The Hook: The Cleanup Function inside useEffect. Why it matters: If you don't clear your setInterval or unsubscribe from a socket here, you’re inviting memory leaks to crash your party. 💡 The "Core Level" Secret: Render vs. Commit To keep your apps buttery smooth, React splits work into two internal phases: Render Phase: Pure calculation. React figures out what changed. It can pause or restart this work if a higher-priority task comes in. Commit Phase: This is where React actually touches the Real DOM. It’s fast, synchronous, and happens in one go. 🧠 The Mental Model Shift In modern React, stop thinking about "methods" and start thinking about Synchronization. useEffect isn't just a lifecycle hook—it’s a tool to synchronize your component with an external system (the API, the DOM, or a Window event). Are you building for performance or just for functionality? Let's discuss in the comments! 👇 #ReactJS #WebDevelopment #FrontendEngineers #CodingTips #JavaScript #SoftwareArchitecture
To view or add a comment, sign in
-
-
⚛️ A small mistake in React cost us performance… here’s what happened. Hey devs 👋 We had a dashboard where everything looked fine… until users increased. Suddenly: ❌ UI started lagging ❌ Filters became slow ❌ Re-renders everywhere 👉 The issue? We were passing fresh objects in props on every render. Something like this: <Child data={{ value: count }} /> Looks harmless… right? 💥 But every render = new object reference → child re-render 💡 What fixed it: ✔ Memoizing data with useMemo ✔ Avoiding inline object creation ✔ Using React.memo properly ⚡ Lesson: React doesn’t compare values… it compares references. Small mistakes → big performance issues. Have you ever faced unnecessary re-renders like this? #reactjs #frontend #performance #javascript #webdevelopment #fullstack #softwareengineering #Coding #TechCareers #Programming #success
To view or add a comment, sign in
-
-
Most React devs use hooks daily… But a lot of us are using them wrong (or at least inefficiently). Here are 5 React Hooks you're probably misusing 👇 1. useEffect: Doing too much If your useEffect looks like a mini backend service… that’s a red flag. 👉 Keep it focused: one responsibility per effect. 👉 Avoid unnecessary dependencies (or missing ones 😬). 2. useState: Over-fragmenting state Multiple useState calls for tightly related data = messy logic. 👉 Consider grouping related state into one object 👉 Or use useReducer for complex flows 3. useMemo: Premature optimization Not everything needs memoization. 👉 If your calculation is cheap, skip it 👉 Overusing useMemo can hurt readability more than it helps performance 4. useCallback: Blind usage Wrapping every function in useCallback ≠ optimization 👉 Only use it when passing functions to memoized components 👉 Otherwise, you're just adding complexity 5. useRef: Misunderstood power It’s not just for DOM access 👉 Great for persisting values without re-renders 👉 Perfect for timers, previous values, or mutable variables 💡 Rule of thumb: If you can’t clearly explain why you're using a hook… you probably don’t need it. What’s a hook mistake you’ve made (or still make)? 😄 #React #WebDevelopment #Frontend #JavaScript #Programming #CodingTips
To view or add a comment, sign in
-
-
🐛 A small bug wasted 3 hours of my time. I was building a React project. Everything looked correct. The API was working. The component was rendering. There were no errors in the console. But the UI was still not updating. For 3 hours, I kept checking the wrong things. Then I finally noticed the problem. I was directly mutating the state instead of creating a new one. Something as small as this: ❌ state.push(newItem) ✅ setState([...state, newItem]) And suddenly, everything started working. That moment reminded me of something important: In development, the biggest problems are often caused by the smallest mistakes. Since then, whenever something doesn’t work, I try to remember: • Don’t panic • Check the basics first • Read the code slowly • Small details matter Because debugging is not just about fixing bugs. It’s about learning how to think better. 💬 What is one bug that taught you an important lesson? #ReactJS #JavaScript #debugging #webdevelopment #developers #learning #softwareengineering
To view or add a comment, sign in
-
You wrapped your component in React.memo… but it still re-renders 🤔 I ran into this more times than I’d like to admit. Everything looks correct. You’re using React.memo. Props don’t seem to change. But the component still re-renders on every parent update. Here’s a simple example: const List = React.memo(({ items }) => { console.log('List render'); return items.map(item => ( <div key={item.id}>{item.name}</div> )); }); function App() { const [count, setCount] = React.useState(0); const items = [{ id: 1, name: 'A' }]; return ( <> <button onClick={() => setCount(count + 1)}> Click </button> <List items={items} /> </> ); } When you click the button the List still re-renders. At first glance, it feels wrong. The data didn’t change… so why did React re-render? The reason is subtle but important: every render creates a new array. So even though the content is the same, the reference is different. [] !== [] And React.memo only does a shallow comparison. So from React’s perspective, the prop did change. One simple fix: const items = React.useMemo(() => [ { id: 1, name: 'A' } ], []); Now the reference stays stable and memoization actually works. Takeaway React.memo is not magic. It only helps if the props you pass are stable. If you create new objects or functions on every render, you’re effectively disabling it without realizing it. This is one of those bugs that doesn’t throw errors… but quietly hurts performance. Have you ever debugged something like this? 👀 #reactjs #javascript #frontend #webdevelopment #performance #reactperformance #softwareengineering #programming #coding #webdev #react #typescript
To view or add a comment, sign in
-
-
React vs. Redux vs. Redux Toolkit: Which should you use? "Do I need Redux?" is still one of the most common questions in frontend development. State management can be overwhelming, but understanding the evolution of these tools makes the choice much clearer. Here is a straightforward breakdown of the big three: 1️⃣ React State & Context (The Foundation) React’s built-in hooks (useState, useReducer, useContext) are often all you need. The Good: Zero extra dependencies. It is perfect for local component state (like form inputs or UI toggles) and low-frequency global state (like user themes or auth status). The Bad: Relying purely on Context for high-frequency, complex global state can lead to unnecessary re-renders and messy prop-drilling. 2️⃣ Classic Redux (The Legacy Heavyweight) Redux revolutionized how we handle global state by introducing a single, predictable source of truth. The Good: Unmatched predictability and incredible developer tools (time-travel debugging is magic). The Bad: The boilerplate. Writing separate files for actions, action types, and reducers slows down development and frustrates teams. 3️⃣ Redux Toolkit / RTK (The Modern Standard) Redux Toolkit is not a replacement for Redux; it is the official, modern way to write it. It takes everything great about Redux and strips away the pain points. The Good: It drastically reduces boilerplate. Features like createSlice automatically generate your actions and reducers. It includes Immer under the hood (allowing you to write simpler, "mutating" logic that updates state immutably), and it ships with RTK Query for incredibly efficient data fetching and caching. The Verdict: If you are starting a new project that genuinely needs Redux, RTK is the only way you should be writing it. 💡 My Rule of Thumb: Start simple. Build with React's built-in state. When your state starts feeling tangled, difficult to track, or requires passing props through five layers of components (Prop Drilling)—it's time to bring in Redux Toolkit. How is your team handling state management these days? Are you firmly on team RTK, or have you pivoted to lighter alternatives like Zustand or Jotai? Let's discuss in the comments! 👇 #ReactJS #Redux #WebDevelopment #Frontend #SoftwareEngineering #JavaScript
To view or add a comment, sign in
-
-
I’ve been go through React hooks lately, and I just finished building a fully functional Todo List that handles complex state updates. 💻 I know this isn't a "polished" UI yet, but through building this project, I’ve learned an immense amount—from the hair-pulling bugs I faced to the satisfaction of finally making the logic work. While a Todo list is a classic "beginner" project, the real architectural lessons happened under the hood: 🔹 Immutability with the Spread Operator: Learning why we never mutate state directly and instead use [...prevTodos] to create clean, predictable UI updates. 🔹 Unique Identifiers: Implementing uuidv4 for keys to ensure React's reconciliation process stays efficient and bug-free. 🔹 Functional State Updates: Using the callback pattern (prevTodos) => ... to ensure I'm always working with the most recent data, avoiding "stale state" traps. 🔹 Conditional Styling: Using ternary operators to toggle text-decoration for a "Mark as Done" feature. Every bug I fixed was a lesson in disguise. Next step: persisting this data with localStorage and then focusing on the CSS! 🏗️ #ReactJS #FrontendDevelopment #Coding #WebDev #StateManagement #LearningByDoing
To view or add a comment, sign in
-
React 19 just mass-deleted half your "optimization" code. And your app got faster because of it. ⚡ For years, React devs have been trained to do one thing — memoize everything. useMemo here. useCallback there. React.memo wrapping every component like bubble wrap. We called it "performance optimization." It was actually performance anxiety. 🧠 The real problem? Most useMemo and useCallback calls do absolutely nothing for performance. They add complexity. They make onboarding painful. And wrong dependency arrays silently break your app. ⚡ React 19 shipped a compiler. Not a plugin. A compiler that automatically figures out: → Which values need memoization → Which components should skip re-renders → Which callbacks are stable All at build time. Zero runtime cost. Zero developer effort. 🔥 Before vs After: React 18: useMemo, useCallback, React.memo everywhere. Dependency arrays at 2 AM. Bugs you can't trace. React 19: Write plain code. The compiler handles the rest. Same performance. Half the code. Zero mental overhead. 🎯 Why this matters: → Junior devs stop guessing where to put useMemo → Code reviews stop being memoization debates → Stale closure bugs just... disappear I removed 23 useMemo/useCallback hooks from one component last week. The diff was -67 lines. It went from "nobody wants to touch this" to "anyone can read this in 30 seconds." The best code isn't the most optimized code. It's the code your entire team ships confidently. React 19 didn't just remove boilerplate. It removed an entire category of bugs. Save this for your team ♻️ #react #javascript #frontend #webdevelopment #softwareengineering #react19 #ES6
To view or add a comment, sign in
-
🧠 The bug wasn’t in my code… It was in my assumption. I spent 2 hours debugging a UI issue where a list wasn’t updating correctly. The logic looked fine. The API response was correct. State was updating. So what was wrong? 👇 👉 I was using the array index as the key in a dynamic list. At first, everything worked. But the moment I added/removes items… things broke in weird ways. 💥 Items re-rendered incorrectly 💥 State got mixed up between components 💥 UI started behaving unpredictably 💡 Lesson learned: Keys in React are not just for removing warnings. They are how React tracks identity. Using index as a key = telling React: "Yeah, these items might change… but pretend they didn’t." 🛠️ Better approach: Always use a unique and stable id from your data. 🧠 Simple way to think: React uses keys like names in a classroom. If everyone has the same name (or changing names), things get chaotic. 🔥 Takeaways: • Avoid index as key (especially in dynamic lists) • Stable identity = predictable UI • Many “random bugs” come from small decisions like this 💬 Have you ever faced a weird UI bug that turned out to be something small? #ReactJS #FrontendDevelopment #JavaScript #WebDev #CodingMistakes
To view or add a comment, sign in
-
🚀 5 React Mistakes I Made as a Beginner (And How to Fix Them) When I first started building with React, I made a lot of mistakes that slowed me down and introduced bugs I couldn't explain. Here are 5 of the most common ones — and how to fix them: ❌ #1 — Not cleaning up useEffect Forget to return a cleanup function? Hello, memory leaks. ✅ Always return a cleanup for timers, event listeners, and subscriptions. ❌ #2 — Using index as a key in lists This breaks React's reconciliation and causes weird UI bugs. ✅ Always use a unique ID from your data as the key prop. ❌ #3 — Calling setState directly inside render This creates an infinite re-render loop. ✅ Keep state updates inside event handlers or useEffect only. ❌ #4 — Fetching data without handling loading and error states Your UI breaks or shows nothing while data loads. ✅ Always manage three states: loading, error, and success. ❌ #5 — Putting everything in one giant component Hard to read, hard to debug, impossible to reuse. ✅ Break your UI into small, focused, reusable components. These mistakes cost me hours of debugging. I hope sharing them saves you that time. If you found this helpful, feel free to repost ♻️ — it might help another developer on their journey. 💬 Which of these mistakes have you made? Drop a comment below! #React #JavaScript #WebDevelopment #Frontend #MERNStack #ReactJS #100DaysOfCode #CodingTips #Developer
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development