# useEffect in React.js [part-2]

### **What is need of useEffect ?**

The need for `useEffect` in React is **to handle side effects** in functional components, allowing you to synchronize your component with an external system *after* rendering, preventing interference with the rendering process. It manages tasks like data fetching, setting up subscriptions (timers, event listeners), and directly manipulating the DOM, replacing class component lifecycle methods (like `componentDidMount`, `componentDidUpdate`) with a unified API.

**What are Side Effects?**  
Side effects are any actions that reach outside the component's scope to interact with something React doesn't directly control, such as:

* **Data Fetching:** Calling APIs to get data.
    
* **DOM Manipulation:** Changing the document title or adding/removing elements.
    
* **Subscriptions:** Setting up timers (setTimeout, setInterval) or event listeners (window resize, keypress).
    
* **Logging:** Logging to the console.
    

---

### **What problem occurs when we do not use useEffect for side effects ?**

**Problem 1:** Infinite Loops 💥

```javascript
function BadComponent() {
  const [count, setCount] = useState(0);
  
  // ❌ This runs DURING render
  setCount(count + 1); // This triggers a re-render
                       // Which runs setCount again
                       // Which triggers another re-render
                       // INFINITE LOOP!
  
  return <div>{count}</div>;
}
```

**What happens:**

* Render starts → `setCount` called → triggers re-render →
    
* New render starts → `setCount` called again → triggers re-render →
    
* **CRASH!** React stops after ~50 iterations to prevent browser freeze
    

---

**Problem 2:** Unpredictable Behavior

```javascript
function BadAPICall() {
  const [data, setData] = useState(null);
  
  // ❌ API call during render
  fetch('/api/data')
    .then(res => res.json())
    .then(setData); // When data arrives, triggers re-render
  
  return <div>{data || 'Loading...'}</div>;
}
```

**What happens:**

* Initial render → fetch called (Request #1 sent)
    
* Parent re-renders for some reason → BadAPICall renders again → fetch called (Request #2 sent)
    
* User clicks button → BadAPICall renders → fetch called (Request #3 sent)
    
* **Result:** Dozens of unnecessary API calls! Your server gets hammered! 📡💥
    

---

**Problem 3:** Race Conditions

```javascript
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  // ❌ Fetch during render
  fetch(`/api/users/${userId}`)
    .then(res => res.json())
    .then(setUser);
  
  return <div>{user?.name}</div>;
}

// User changes from ID 1 → ID 5 quickly
// Request for user 1 sent (takes 500ms)
// Request for user 5 sent (takes 100ms)
// User 5 displays ✓
// Then user 1 response arrives and overwrites it ❌
// Wrong user shown!
```

---

### React's Rendering Process

Here's what React actually does during a render:

```javascript
// React's internal process (simplified)
function reactRenderProcess() {
  // Phase 1: RENDER (Pure calculation)
  const virtualDOM = YourComponent(); // Just calls your function
  
  // Phase 2: Compare with previous render
  const changes = compareVirtualDOMs(oldVirtualDOM, virtualDOM);
  
  // Phase 3: COMMIT (Actually update the browser)
  applyChangesToRealDOM(changes);
  
  // Phase 4: Run effects
  runAllUseEffects(); // ← This is where side effects happen!
}
```

**During Phase 1 (Render):**

* React might call your component **multiple times**
    
* React might **throw away** the result without committing it
    
* React needs to be able to pause and resume
    
* **This is why it must be <mark>pure!</mark>**
    

---

## Simple Analogy 🎨

Think of rendering like a painter **planning** a painting:

**During Rendering (Planning Phase):**

* "I'll paint a tree here, a house there..."
    
* Just thinking and sketching
    
* Might change mind and start over
    
* **Don't order paint, don't call suppliers!**
    

**After Rendering (Execution Phase - useEffect):**

* Plan is finalized
    
* Painting is on the wall
    
* **Now** you can order more paint, call the client, post on social media
    
* These are "side effects"
    

**Summary: Why Not Update State During Rendering?**

1. **Renders can happen multiple times** - React might render but not commit
    
2. **Renders must be predictable** - <mark>Same input = same output</mark>
    
3. **Prevents infinite loops** - State updates during render cause re-renders
    
4. **Avoids duplicate side effects** - API calls, subscriptions would run repeatedly
    
5. **Enables React features** - Concurrent rendering, Suspense, time-slicing
    

**The rule:** Rendering = pure calculation. Side effects = useEffect.
