> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anujpandey.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Components

# 📘 React Components (Functional & Class Basics) — Complete Theory Guide

***

## 1. 🔹 Introduction

### ✅ What are Components?

In React, **components** are the fundamental building blocks of a UI.
They are **reusable, independent pieces of code** that return UI elements.

There are two main types:

* **Functional Components** (modern, preferred)
* **Class Components** (legacy but still important for understanding React evolution)

***

### 💡 Why Components are Important

* Enable **modular architecture**
* Promote **code reuse**
* Improve **maintainability**
* Allow **separation of concerns**
* Help manage **UI logic efficiently**

***

### 📍 When & Why We Use Components

Use components when:

* UI can be broken into smaller parts (e.g., Navbar, Card, Button)
* You want reusable UI patterns
* You need to isolate logic (state, effects)

👉 Example:
Instead of writing a full page in one file, split into:

* `<Header />`
* `<Sidebar />`
* `<ProductCard />`

***

## 2. ⚙️ Concepts / Internal Workings

***

### 🔹 2.1 Functional Components

A **functional component** is simply a JavaScript function that returns JSX.

```jsx theme={null}
function Welcome() {
  return <h1>Hello, World!</h1>;
}
```

#### Key Characteristics:

* Stateless (initially), but now use **Hooks**
* Lightweight and faster
* Easier to read and test

***

### 🔹 2.2 Class Components

A **class component** is a JavaScript class that extends `React.Component`.

```jsx theme={null}
import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}
```

#### Key Characteristics:

* Uses lifecycle methods
* Has `this` binding
* Manages state via `this.state`

***

### 🔹 2.3 JSX → React Elements → Virtual DOM

#### Flow:

1. JSX is written
2. Transpiled to `React.createElement`
3. Creates Virtual DOM
4. React compares (Diffing)
5. Updates real DOM (Reconciliation)

```jsx theme={null}
const element = <h1>Hello</h1>;

// becomes:
React.createElement('h1', null, 'Hello');
```

***

### 🔹 2.4 Props (Input to Components)

Props = Read-only data passed from parent to child.

```jsx theme={null}
function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}
```

***

### 🔹 2.5 State (Internal Data)

State is mutable data inside a component.

#### Functional (Hooks):

```jsx theme={null}
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```

#### Class:

```jsx theme={null}
this.state = { count: 0 };
this.setState({ count: this.state.count + 1 });
```

***

### 🔹 2.6 Lifecycle (Class Components)

Important lifecycle methods:

| Phase      | Method                 |
| ---------- | ---------------------- |
| Mounting   | `componentDidMount`    |
| Updating   | `componentDidUpdate`   |
| Unmounting | `componentWillUnmount` |

***

### 🔹 2.7 Functional Alternative to Lifecycle (Hooks)

* `useEffect()` replaces lifecycle methods

```jsx theme={null}
useEffect(() => {
  console.log("Component Mounted");
}, []);
```

***

### 🔹 2.8 Component Tree & Re-rendering

* React builds a **component tree**
* Re-renders happen when:

  * Props change
  * State changes

***

### 🔹 2.9 Relationship with Other React Features

| Feature      | Relationship                  |
| ------------ | ----------------------------- |
| Hooks        | Used in functional components |
| Context API  | Share data across components  |
| Redux        | External state management     |
| React Router | Component-based navigation    |

***

## 3. 🧪 Syntax & Examples

***

### 🔹 3.1 Basic Functional Component

```jsx theme={null}
function App() {
  return <h1>My App</h1>;
}
```

***

### 🔹 3.2 Arrow Function Component

```jsx theme={null}
const App = () => <h1>Hello</h1>;
```

***

### 🔹 3.3 Component with Props

```jsx theme={null}
const User = ({ name }) => {
  return <h2>{name}</h2>;
};
```

***

### 🔹 3.4 Nested Components

```jsx theme={null}
function App() {
  return (
    <div>
      <Header />
      <Footer />
    </div>
  );
}
```

***

### 🔹 3.5 Conditional Rendering

```jsx theme={null}
function Status({ isLoggedIn }) {
  return isLoggedIn ? <h1>Welcome</h1> : <h1>Please Login</h1>;
}
```

***

### 🔹 3.6 List Rendering

```jsx theme={null}
const items = ['A', 'B', 'C'];

items.map((item, index) => <li key={index}>{item}</li>);
```

***

### 🔹 3.7 Class Component Example

```jsx theme={null}
class Counter extends React.Component {
  state = { count: 0 };

  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        {this.state.count}
      </button>
    );
  }
}
```

***

### 🔹 3.8 Controlled Component

```jsx theme={null}
function Input() {
  const [value, setValue] = useState("");

  return (
    <input value={value} onChange={(e) => setValue(e.target.value)} />
  );
}
```

***

## 4. ⚠️ Edge Cases / Common Mistakes

***

### ❌ 4.1 Mutating State Directly

```jsx theme={null}
// WRONG
state.count = 1;
```

👉 Always use setter:

```jsx theme={null}
setCount(1);
```

***

### ❌ 4.2 Missing `key` in Lists

```jsx theme={null}
items.map(item => <li>{item}</li>) // ❌
```

👉 Fix:

```jsx theme={null}
items.map(item => <li key={item}>{item}</li>)
```

***

### ❌ 4.3 Infinite Re-renders

```jsx theme={null}
setCount(count + 1); // inside render ❌
```

***

### ❌ 4.4 `this` Binding Issues (Class)

```jsx theme={null}
this.handleClick = this.handleClick.bind(this);
```

***

### ❌ 4.5 Incorrect useEffect Dependencies

```jsx theme={null}
useEffect(() => {
  fetchData();
}, []); // missing dependencies ❌
```

***

### ❌ 4.6 Re-rendering All Components

* Happens when parent state updates unnecessarily

👉 Fix:

* Use `React.memo`
* Split components

***

## 5. ✅ Best Practices

***

### 🔹 5.1 Prefer Functional Components

* Cleaner
* Hooks-based
* Future-proof

***

### 🔹 5.2 Keep Components Small & Focused

* One responsibility per component

***

### 🔹 5.3 Use Destructuring

```jsx theme={null}
const Card = ({ title }) => <h1>{title}</h1>;
```

***

### 🔹 5.4 Use Proper Naming

* PascalCase for components:

  * `UserCard`
  * `Navbar`

***

### 🔹 5.5 Avoid Inline Functions (Performance)

```jsx theme={null}
<button onClick={() => doSomething()} />
```

👉 Use:

```jsx theme={null}
const handleClick = () => doSomething();
```

***

### 🔹 5.6 Use Memoization

```jsx theme={null}
export default React.memo(Component);
```

***

### 🔹 5.7 Avoid Prop Drilling

👉 Use:

* Context API
* State management tools

***

### 🔹 5.8 Use Keys Properly

* Never use index unless necessary
* Use unique IDs

***

### 🔹 5.9 Optimize Re-renders

* `useMemo`
* `useCallback`

***

### 🔹 5.10 Folder Structure

```
/components
  /Button
    Button.jsx
    Button.css
```

***

## 📌 Summary

* Components are the **core of React architecture**
* Functional components + Hooks are the **modern standard**
* Class components are **important for legacy understanding**
* Proper structure and optimization lead to **scalable apps**

***

Below is a **senior-level conceptual interview set** on **React Components (Functional & Class Basics)** — focused on *depth, internal behavior, trade-offs, and real-world thinking*.

***

# 🧠 Advanced React Components — Interview Questions & Answers

***

## 1. Why did React shift from Class Components to Functional Components with Hooks?

### ✅ Strong Answer

The shift was driven by **simplicity, composability, and better logic reuse**.

### 🔍 Key Reasons

1. **Separation of Concerns**

   * Class components split logic across lifecycle methods
   * Hooks allow grouping related logic together

2. **Avoid `this` Complexity**

   * Class components require binding
   * Functional components eliminate `this`

3. **Better Code Reuse**

   * Hooks replace HOCs and render props

4. **Less Boilerplate**

### 💡 Example Comparison

**Class (fragmented logic):**

```jsx theme={null}
componentDidMount() {
  fetchData();
}

componentDidUpdate() {
  fetchData();
}
```

**Functional (cohesive logic):**

```jsx theme={null}
useEffect(() => {
  fetchData();
}, [dependency]);
```

### ⚖️ Trade-off

* Hooks introduce **dependency array complexity**
* Requires understanding of closures

***

## 2. How does React internally treat Functional vs Class components?

### ✅ Strong Answer

Internally, both are treated as **units that produce React elements**, but:

* **Class Components** → instantiated with `new`
* **Functional Components** → invoked as plain functions

### 🔍 Internal Differences

| Aspect        | Functional                  | Class                   |
| ------------- | --------------------------- | ----------------------- |
| Execution     | Function call               | Class instance          |
| State storage | Hook list (linked to fiber) | Instance (`this.state`) |
| Lifecycle     | useEffect hooks             | Lifecycle methods       |

### 🧠 Fiber Insight

React stores hooks in a **linked list inside Fiber nodes**, maintaining order across renders.

***

## 3. Why must Hooks be called unconditionally and in the same order?

### ✅ Strong Answer

React relies on **call order to map hooks to internal state slots**.

### 🔍 Internal Reason

React does NOT track hooks by name — it tracks by **position**.

```jsx theme={null}
// ❌ WRONG
if (condition) {
  useEffect(() => {});
}
```

### 💡 Why it breaks?

* On next render, hook order changes
* React mismatches state

***

## 4. What actually triggers a component re-render?

### ✅ Strong Answer

A component re-renders when:

1. **State changes**
2. **Props change**
3. **Parent re-renders**
4. **Context changes**

### 🔍 Important Insight

React does NOT deeply compare values — it relies on **reference equality**.

```jsx theme={null}
setState({}) // always new reference → re-render
```

### ⚖️ Optimization

* `React.memo`
* `useMemo`
* `useCallback`

***

## 5. Why is direct state mutation a critical issue?

### ✅ Strong Answer

React relies on **immutability for change detection**.

### 🔍 Problem

```jsx theme={null}
state.count = 1; // ❌ no re-render
```

React cannot detect the change because:

* Reference is unchanged

### ✅ Correct

```jsx theme={null}
setCount(prev => prev + 1);
```

***

## 6. How does React reconcile component trees?

### ✅ Strong Answer

React uses a **diffing algorithm (Reconciliation)**:

1. Compare old vs new Virtual DOM
2. Identify minimal changes
3. Update real DOM efficiently

### 🔍 Key Assumptions

* Elements of different types → replace
* Keys help track identity

***

## 7. Why are keys critical in list rendering?

### ✅ Strong Answer

Keys help React **preserve component identity across renders**.

### 🔍 Problem Without Keys

```jsx theme={null}
items.map((item, index) => <Item key={index} />)
```

* Causes incorrect DOM reuse
* Leads to bugs (especially in forms)

### 💡 Real Issue

* Input values shifting unexpectedly

***

## 8. Explain the difference between controlled and uncontrolled components.

### ✅ Strong Answer

| Type        | Controlled   | Uncontrolled |
| ----------- | ------------ | ------------ |
| Data Source | React state  | DOM          |
| Control     | Full control | Less control |

### 💡 Example

```jsx theme={null}
<input value={value} onChange={...} />
```

### ⚖️ Trade-off

* Controlled → predictable but verbose
* Uncontrolled → simpler but less flexible

***

## 9. What are the hidden pitfalls of useEffect?

### ✅ Strong Answer

1. **Stale closures**
2. Missing dependencies
3. Infinite loops

### 💡 Example

```jsx theme={null}
useEffect(() => {
  console.log(count);
}, []); // stale value
```

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  console.log(count);
}, [count]);
```

***

## 10. Why do functions inside components cause performance issues?

### ✅ Strong Answer

Functions are recreated on every render → new reference → triggers child re-renders.

```jsx theme={null}
<button onClick={() => doSomething()} />
```

### ✅ Fix

```jsx theme={null}
const handleClick = useCallback(() => {}, []);
```

***

## 11. How does React.memo work internally?

### ✅ Strong Answer

* Performs **shallow comparison of props**
* Skips re-render if props unchanged

### ⚠️ Limitation

```jsx theme={null}
<Child obj={{ a: 1 }} />
```

* Always re-renders due to new reference

***

## 12. When would you still use Class Components today?

### ✅ Strong Answer

* Legacy codebases
* Error boundaries (before hooks alternative)

```jsx theme={null}
componentDidCatch(error, info) {}
```

### ⚖️ Trade-off

* More verbose
* Less composable

***

## 13. Explain lifting state up and its trade-offs.

### ✅ Strong Answer

Moving shared state to the closest common ancestor.

### 💡 Problem

* Leads to **prop drilling**

### ✅ Alternative

* Context API
* State libraries

***

## 14. What is prop drilling and how do you avoid it?

### ✅ Strong Answer

Passing props through multiple layers unnecessarily.

```jsx theme={null}
<App → A → B → C → D />
```

### ✅ Solutions

* Context API
* Redux / Zustand

***

## 15. How do closures affect React components?

### ✅ Strong Answer

Closures can capture **stale state values**.

```jsx theme={null}
setTimeout(() => {
  console.log(count);
}, 1000);
```

### ✅ Fix

```jsx theme={null}
setCount(prev => prev + 1);
```

***

## 16. Why is component composition preferred over inheritance in React?

### ✅ Strong Answer

React promotes **composition for flexibility**.

### 💡 Example

```jsx theme={null}
<Card>
  <Button />
</Card>
```

### ⚖️ Why not inheritance?

* Tight coupling
* Less reusable

***

## 17. How does React batch state updates?

### ✅ Strong Answer

React groups multiple updates into a single render for performance.

```jsx theme={null}
setCount(1);
setCount(2);
```

→ One render

### 🔍 React 18+

* Automatic batching even in async code

***

## 18. What are render phases vs commit phases?

### ✅ Strong Answer

| Phase  | Description       |
| ------ | ----------------- |
| Render | Calculate changes |
| Commit | Apply to DOM      |

### 🔍 Insight

* Render phase can be interrupted
* Commit phase is synchronous

***

## 19. Why can excessive component re-rendering become a bottleneck?

### ✅ Strong Answer

Because React:

* Re-executes component functions
* Recalculates Virtual DOM

### 🔍 Real-world Impact

* Slow UI in large trees

### ✅ Fix

* Memoization
* Splitting components

***

## 20. How do you decide component boundaries in a real application?

### ✅ Strong Answer

Based on:

1. **Reusability**
2. **Separation of concerns**
3. **Performance isolation**

### 💡 Bad Design

* One giant component

### 💡 Good Design

* Small, focused, composable components

***

# 📌 Final Takeaway

Senior-level understanding of components is about:

* Thinking in **render cycles**
* Understanding **React internals (Fiber, reconciliation)**
* Managing **performance trade-offs**
* Designing **scalable component architecture**

***

Below is a **senior-level MCQ set (18 questions)** on **React Components (Functional & Class Basics)**.
Each question targets **deep understanding, edge cases, and real-world behavior**.

***

# 🧠 Advanced React Components — MCQs

***

## 1. What happens when you update state with the same value?

```jsx theme={null}
const [count, setCount] = useState(0);
setCount(0);
```

### Options:

A. Component always re-renders
B. Component never re-renders
C. React may skip re-render using Object.is comparison
D. React throws an error

### ✅ Correct Answer: C

### 💡 Explanation:

React uses **Object.is comparison**. If the value is identical, React **bails out of re-render**.

### ❌ Why others are wrong:

* A: Incorrect — React optimizes unnecessary renders
* B: Not always true (edge cases like forced updates)
* D: No error occurs

***

## 2. What is the output?

```jsx theme={null}
function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(1);
  }, []);

  console.log(count);
  return null;
}
```

### Options:

A. Logs 0
B. Logs 1
C. Logs 0 then 1
D. Infinite loop

### ✅ Correct Answer: C

### 💡 Explanation:

* Initial render → logs `0`
* Effect runs after render → updates state → re-render → logs `1`

### ❌ Others:

* A/B: Ignore lifecycle timing
* D: No dependency loop

***

## 3. Why is this problematic?

```jsx theme={null}
useEffect(() => {
  fetchData();
}, []);
```

### Options:

A. It runs too many times
B. It may use stale variables
C. It blocks rendering
D. It causes memory leaks always

### ✅ Correct Answer: B

### 💡 Explanation:

The empty dependency array can cause **stale closure issues** if `fetchData` depends on changing values.

***

## 4. What happens here?

```jsx theme={null}
const obj = { a: 1 };
setState(obj);
setState(obj);
```

### Options:

A. Two re-renders
B. One re-render
C. No re-render
D. Error

### ✅ Correct Answer: B

### 💡 Explanation:

Same reference → React batches updates → single re-render.

***

## 5. What is the issue with index as key?

```jsx theme={null}
items.map((item, index) => <Item key={index} />)
```

### Options:

A. Performance issue only
B. Causes incorrect DOM reuse
C. Causes syntax error
D. Prevents rendering

### ✅ Correct Answer: B

### 💡 Explanation:

Index keys break **component identity**, causing UI bugs during reorder.

***

## 6. What happens when parent re-renders?

### Options:

A. Only changed children render
B. All children render by default
C. React skips all children
D. Only stateful children render

### ✅ Correct Answer: B

### 💡 Explanation:

React **re-runs all child components** unless optimized.

***

## 7. What is wrong here?

```jsx theme={null}
if (condition) {
  useEffect(() => {});
}
```

### Options:

A. Nothing
B. Causes memory leak
C. Breaks hook order
D. Slows performance

### ✅ Correct Answer: C

### 💡 Explanation:

Hooks must be called **in the same order every render**.

***

## 8. Why does this re-render child?

```jsx theme={null}
<Child data={{ a: 1 }} />
```

### Options:

A. Because object is mutable
B. New reference each render
C. React deep compares
D. Child forces update

### ✅ Correct Answer: B

***

## 9. What happens in this case?

```jsx theme={null}
setCount(count + 1);
setCount(count + 1);
```

### Options:

A. +2 increment
B. +1 increment
C. Infinite loop
D. No change

### ✅ Correct Answer: B

### 💡 Explanation:

Both updates use **same stale value**.

***

## 10. Correct fix?

### Options:

A. `setCount(count + 2)`
B. `setCount(prev => prev + 1)` twice
C. `setCount(() => count + 1)`
D. UseEffect

### ✅ Correct Answer: B

***

## 11. Why is this inefficient?

```jsx theme={null}
<button onClick={() => handleClick()} />
```

### Options:

A. Syntax error
B. Recreates function every render
C. Blocks UI
D. Causes memory leak

### ✅ Correct Answer: B

***

## 12. What does React.memo NOT handle well?

### Options:

A. Primitive props
B. Stable references
C. Inline objects/functions
D. Static components

### ✅ Correct Answer: C

***

## 13. What happens here?

```jsx theme={null}
const [state, setState] = useState({ count: 0 });
setState({ count: 0 });
```

### Options:

A. No re-render
B. Re-render occurs
C. Error
D. Infinite loop

### ✅ Correct Answer: B

### 💡 Explanation:

New object reference → triggers render.

***

## 14. Why is this unsafe?

```jsx theme={null}
state.count++;
setState(state);
```

### Options:

A. Syntax issue
B. Mutation breaks React detection
C. Causes crash
D. Async issue

### ✅ Correct Answer: B

***

## 15. What is true about class vs functional?

### Options:

A. Class is faster
B. Functional supports hooks
C. Class supports hooks
D. Functional cannot manage state

### ✅ Correct Answer: B

***

## 16. What happens during reconciliation?

### Options:

A. Full DOM replacement
B. Minimal updates via diffing
C. No updates
D. Random updates

### ✅ Correct Answer: B

***

## 17. What is the problem here?

```jsx theme={null}
useEffect(() => {
  setCount(count + 1);
}, [count]);
```

### Options:

A. Runs once
B. Infinite loop
C. No update
D. Error

### ✅ Correct Answer: B

***

## 18. Why prefer composition over inheritance?

### Options:

A. Less code
B. More flexibility and reuse
C. Required by React
D. Better performance only

### ✅ Correct Answer: B

***

# 📌 Final Insight

These questions test:

* **Render cycle understanding**
* **Hook behavior & pitfalls**
* **Reconciliation & identity**
* **Performance reasoning**
* **Real-world debugging mindset**

***

Below is a **senior-level coding problem set (18 problems)** focused on **React Components (Functional & Class Basics)**.
Each problem simulates **real-world scenarios**, emphasizes **thinking**, and includes **edge cases + reasoning**.

***

# 🧠 Advanced React Component Coding Problems

***

## 1. 🔄 Smart Counter with Sync Issues

### 🧩 Problem

Build a counter that:

* Increments correctly even with rapid clicks
* Logs correct value after async delay

### ⚠️ Constraints

* Avoid stale state
* Must handle async updates

### ✅ Expected Behavior

* Clicking 3 times → count = 3
* Console logs correct count

### ⚠️ Edge Cases

* Rapid clicks
* Async delays

### 💡 Solution

```jsx theme={null}
const Counter = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(prev => prev + 1);

    setTimeout(() => {
      console.log("Latest:", count); // stale
    }, 1000);
  };

  return <button onClick={handleClick}>{count}</button>;
};
```

### 🧠 Fix Explanation

Use ref to avoid stale closure:

```jsx theme={null}
const countRef = useRef(count);
useEffect(() => {
  countRef.current = count;
}, [count]);
```

***

## 2. 🔁 Prevent Unnecessary Re-renders

### 🧩 Problem

Optimize a child component so it doesn't re-render unnecessarily.

### Constraints

* Parent updates frequently

### 💡 Solution

```jsx theme={null}
const Child = React.memo(({ data }) => {
  console.log("Rendered");
  return <div>{data.value}</div>;
});
```

### 🧠 Explanation

Use `React.memo` + stable props (`useMemo`)

***

## 3. 🧠 Derived State Bug

### Problem

Sync prop → state without causing inconsistency.

### Edge Case

* Prop updates asynchronously

### ❌ Bad

```jsx theme={null}
const [value, setValue] = useState(props.value);
```

### ✅ Solution

```jsx theme={null}
useEffect(() => {
  setValue(props.value);
}, [props.value]);
```

***

## 4. 🔍 Search with Debounce

### Problem

Create search input with debounce.

### Constraints

* Avoid excessive API calls

### 💡 Solution

```jsx theme={null}
useEffect(() => {
  const id = setTimeout(() => {
    fetchResults(query);
  }, 500);

  return () => clearTimeout(id);
}, [query]);
```

***

## 5. 📦 Dynamic Form Builder

### Problem

Render form fields dynamically based on config.

### Edge Case

* Unknown field types

### Solution Idea

Use component mapping:

```jsx theme={null}
const components = {
  text: TextInput,
  checkbox: Checkbox,
};
```

***

## 6. 🔐 Controlled vs Uncontrolled Hybrid

### Problem

Input should:

* Work controlled OR uncontrolled

### Solution

```jsx theme={null}
const isControlled = value !== undefined;
```

***

## 7. 🔄 Infinite Loop Debugging

### Problem

Fix infinite re-render:

```jsx theme={null}
useEffect(() => {
  setData(fetchData());
}, [data]);
```

### Solution

* Remove `data` dependency
* Use proper trigger

***

## 8. 🧩 Compound Components Pattern

### Problem

Build `<Tabs>` system:

```jsx theme={null}
<Tabs>
  <Tabs.List />
  <Tabs.Panel />
</Tabs>
```

### Solution Idea

Use Context API

***

## 9. 📊 Expensive Calculation Optimization

### Problem

Prevent heavy recalculation

### Solution

```jsx theme={null}
const result = useMemo(() => expensiveFn(data), [data]);
```

***

## 10. 🔁 Shared State Between Siblings

### Problem

Two components share state

### Solution

Lift state up OR Context

***

## 11. 🧵 Async Data Race Condition

### Problem

Avoid outdated API results overriding new ones

### Solution

```jsx theme={null}
let active = true;

if (active) setData(result);

return () => active = false;
```

***

## 12. 🧠 Custom Hook Extraction

### Problem

Extract reusable logic (e.g., window resize)

### Solution

```jsx theme={null}
function useWindowSize() {}
```

***

## 13. 🎯 Conditional Rendering Trap

### Problem

Prevent component losing state when hidden

### ❌ Bad

```jsx theme={null}
{show && <Component />}
```

### ✅ Solution

Keep mounted + toggle visibility

***

## 14. 🔑 List Reordering Bug

### Problem

Fix UI glitch when reordering items

### Solution

Use stable unique keys (IDs)

***

## 15. 🧪 Error Boundary Implementation

### Problem

Catch runtime errors

### Solution (Class Only)

```jsx theme={null}
class ErrorBoundary extends React.Component {
  componentDidCatch(error) {}
}
```

***

## 16. 🧩 Component Composition Refactor

### Problem

Refactor large component into smaller ones

### Solution

* Split by responsibility
* Extract reusable pieces

***

## 17. ⚡ Batch Updates Understanding

### Problem

Explain why:

```jsx theme={null}
setCount(1);
setCount(2);
```

→ Only one render

### Solution

React batching

***

## 18. 🔄 Function Identity Bug

### Problem

Child re-renders due to function prop

### Solution

```jsx theme={null}
const fn = useCallback(() => {}, []);
```

***

# 📌 Final Insight

These problems test:

* **State correctness under async conditions**
* **Render optimization thinking**
* **Component architecture design**
* **Real-world debugging skills**

***

Below are **18 senior-level debugging challenges** based on **React Components (functional & class basics)**.
Each mirrors **real production bugs** — subtle, non-trivial, and rooted in **React behavior**.

***

# 🐞 Advanced React Debugging Challenges

***

## 1. 🔁 Stale Closure in Async Callback

### ❌ Buggy Code

```jsx theme={null}
function Counter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setTimeout(() => {
      console.log(count);
    }, 1000);
  };

  return <button onClick={handleClick}>{count}</button>;
}
```

### ❗ What’s Wrong

Logs stale `count` value.

### 🤔 Why It Happens

Closure captures **value at render time**, not latest state.

### ✅ Fix

```jsx theme={null}
const countRef = useRef(count);

useEffect(() => {
  countRef.current = count;
}, [count]);

setTimeout(() => {
  console.log(countRef.current);
}, 1000);
```

### 🧠 Best Practice

* Use `useRef` or functional updates for async logic

***

## 2. 🔄 Infinite useEffect Loop

### ❌ Code

```jsx theme={null}
useEffect(() => {
  setData(fetchData());
}, [data]);
```

### ❗ Problem

Infinite re-render loop

### 🤔 Why

* `setData` updates `data`
* dependency triggers effect again

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  setData(fetchData());
}, []);
```

### 🧠 Best Practice

* Avoid updating dependencies inside effect

***

## 3. 📦 Re-render due to Object Props

### ❌ Code

```jsx theme={null}
<Child config={{ theme: "dark" }} />
```

### ❗ Problem

Child re-renders every time

### 🤔 Why

New object reference each render

### ✅ Fix

```jsx theme={null}
const config = useMemo(() => ({ theme: "dark" }), []);
<Child config={config} />
```

### 🧠 Best Practice

* Memoize objects/functions passed as props

***

## 4. 🔑 List Reordering Bug

### ❌ Code

```jsx theme={null}
items.map((item, index) => <Item key={index} />)
```

### ❗ Problem

UI glitches on reorder

### 🤔 Why

Index doesn’t preserve identity

### ✅ Fix

```jsx theme={null}
items.map(item => <Item key={item.id} />)
```

### 🧠 Best Practice

* Always use stable unique keys

***

## 5. 🧠 Incorrect State Mutation

### ❌ Code

```jsx theme={null}
state.count++;
setState(state);
```

### ❗ Problem

Component may not re-render

### 🤔 Why

Reference unchanged → React doesn’t detect change

### ✅ Fix

```jsx theme={null}
setState(prev => ({ ...prev, count: prev.count + 1 }));
```

***

## 6. ⚡ Double State Update Bug

### ❌ Code

```jsx theme={null}
setCount(count + 1);
setCount(count + 1);
```

### ❗ Problem

Only increments once

### 🤔 Why

Both use same stale value

### ✅ Fix

```jsx theme={null}
setCount(prev => prev + 1);
setCount(prev => prev + 1);
```

***

## 7. 🧩 Missing Dependency in useEffect

### ❌ Code

```jsx theme={null}
useEffect(() => {
  fetchData(userId);
}, []);
```

### ❗ Problem

Doesn’t update when `userId` changes

### 🤔 Why

Dependency missing

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  fetchData(userId);
}, [userId]);
```

***

## 8. 🔄 Function Prop Causing Re-render

### ❌ Code

```jsx theme={null}
<Child onClick={() => doSomething()} />
```

### ❗ Problem

Child re-renders unnecessarily

### 🤔 Why

New function reference each render

### ✅ Fix

```jsx theme={null}
const handleClick = useCallback(() => doSomething(), []);
<Child onClick={handleClick} />
```

***

## 9. 🧪 useEffect Cleanup Missing

### ❌ Code

```jsx theme={null}
useEffect(() => {
  window.addEventListener("resize", handleResize);
}, []);
```

### ❗ Problem

Memory leak

### 🤔 Why

Listener never removed

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  window.addEventListener("resize", handleResize);
  return () => window.removeEventListener("resize", handleResize);
}, []);
```

***

## 10. 🧠 Derived State Desync

### ❌ Code

```jsx theme={null}
const [value, setValue] = useState(props.value);
```

### ❗ Problem

State not updating with props

### 🤔 Why

Initial value only used once

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  setValue(props.value);
}, [props.value]);
```

***

## 11. 🔍 Conditional Hook Usage

### ❌ Code

```jsx theme={null}
if (isVisible) {
  useEffect(() => {});
}
```

### ❗ Problem

Hook order breaks

### 🤔 Why

Hooks must run in same order

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  if (isVisible) {
    // logic
  }
}, [isVisible]);
```

***

## 12. ⚠️ Expensive Calculation Every Render

### ❌ Code

```jsx theme={null}
const result = expensiveFn(data);
```

### ❗ Problem

Performance issue

### 🤔 Why

Runs on every render

### ✅ Fix

```jsx theme={null}
const result = useMemo(() => expensiveFn(data), [data]);
```

***

## 13. 🔄 Component Losing State

### ❌ Code

```jsx theme={null}
{show && <Form />}
```

### ❗ Problem

State resets on toggle

### 🤔 Why

Component unmounts

### ✅ Fix

```jsx theme={null}
<Form hidden={!show} />
```

***

## 14. 🧵 Async Race Condition

### ❌ Code

```jsx theme={null}
useEffect(() => {
  fetch(`/api?q=${query}`).then(setData);
}, [query]);
```

### ❗ Problem

Older responses overwrite newer

### 🤔 Why

Async race

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  let active = true;

  fetch(`/api?q=${query}`).then(res => {
    if (active) setData(res);
  });

  return () => (active = false);
}, [query]);
```

***

## 15. 🔁 Unnecessary Parent Re-renders

### ❌ Code

```jsx theme={null}
const value = { count };
```

### ❗ Problem

Triggers children updates

### 🤔 Why

New object each render

### ✅ Fix

```jsx theme={null}
const value = useMemo(() => ({ count }), [count]);
```

***

## 16. 🧠 setState Async Misunderstanding

### ❌ Code

```jsx theme={null}
setCount(count + 1);
console.log(count);
```

### ❗ Problem

Logs old value

### 🤔 Why

State updates are async

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  console.log(count);
}, [count]);
```

***

## 17. 🧩 Class Component `this` Issue

### ❌ Code

```jsx theme={null}
handleClick() {
  console.log(this.state);
}
```

### ❗ Problem

`this` undefined

### 🤔 Why

Not bound

### ✅ Fix

```jsx theme={null}
this.handleClick = this.handleClick.bind(this);
```

OR

```jsx theme={null}
handleClick = () => {}
```

***

## 18. ⚡ React.memo Ineffective

### ❌ Code

```jsx theme={null}
<Child data={{ value: count }} />
```

### ❗ Problem

Memo not working

### 🤔 Why

New object every render

### ✅ Fix

```jsx theme={null}
const data = useMemo(() => ({ value: count }), [count]);
```

***

# 📌 Final Takeaways

These bugs reflect real-world issues:

* **Closures & async traps**
* **Reference equality pitfalls**
* **Hook rules violations**
* **Reconciliation misunderstandings**
* **Performance bottlenecks**

***

Below is a **production-grade machine coding set (18 problems)** focused on **React Components (Functional & Class Basics)**.
These reflect **real-world systems, FAANG-style interviews, and production architecture thinking**.

***

# 🏗️ Advanced React Machine Coding Problems

***

## 1. 🧠 Smart Autocomplete with Caching

### 📌 Requirements

* Input field with suggestions
* Fetch suggestions via API
* Cache previous queries
* Highlight matched text

### ⚙️ UI Behavior

* Debounced typing (300ms)
* Loading indicator
* Keyboard navigation (↑ ↓ Enter)

### 🔄 State/Data Flow

* `query`, `results`, `cache`, `loading`, `activeIndex`

### ⚠️ Edge Cases

* Empty input
* Rapid typing → race conditions
* Same query repeated

### 🚀 Performance

* Debounce
* Memoized cache

### 🏗️ Architecture

* `SearchBox`
* `SuggestionList`
* `useDebounce`, `useCache`

### 🧠 Approach

1. Capture input
2. Debounce API call
3. Store results in cache
4. Handle keyboard navigation

***

## 2. 📊 Virtualized Infinite List

### 📌 Requirements

* Render 10k+ items efficiently
* Infinite scroll loading

### ⚙️ UI Behavior

* Only visible items rendered
* Smooth scroll

### 🔄 State

* `items`, `scrollTop`, `visibleRange`

### ⚠️ Edge Cases

* Fast scroll jumps
* Dynamic item heights

### 🚀 Performance

* Windowing (virtualization)

### 🏗️ Architecture

* `ListContainer`
* `ListItem`

### 🧠 Approach

* Calculate visible indices
* Render subset only

***

## 3. 🧾 Multi-step Form Wizard

### 📌 Requirements

* Step-based navigation
* Validation per step
* Save progress

### ⚙️ UI

* Next/Prev buttons
* Progress indicator

### 🔄 State

* Centralized form state

### ⚠️ Edge Cases

* Back navigation retains data
* Validation errors

### 🏗️ Architecture

* `Wizard`
* `Step`
* Context for state

***

## 4. 🔁 Real-time Chat UI

### 📌 Requirements

* Message list
* Auto-scroll
* Typing indicator

### ⚙️ Behavior

* New messages push bottom

### ⚠️ Edge Cases

* Scroll position preservation
* Duplicate messages

### 🚀 Performance

* Virtualization for large chats

***

## 5. 🧠 Undo/Redo State Manager

### 📌 Requirements

* Maintain history
* Undo/redo actions

### 🔄 State

* `past`, `present`, `future`

### ⚠️ Edge Cases

* New action clears future

### 🧠 Approach

* Stack-based state

***

## 6. 📦 Dynamic Dashboard Layout

### 📌 Requirements

* Drag & drop widgets
* Resizable grid

### ⚠️ Edge Cases

* Collision handling

### 🏗️ Architecture

* `Dashboard`
* `Widget`

***

## 7. 🔐 Role-based Component Rendering

### 📌 Requirements

* Render UI based on user roles

### ⚠️ Edge Cases

* Unauthorized access

### 🧠 Approach

* HOC or wrapper component

***

## 8. 🧾 Table with Sorting, Filtering, Pagination

### 📌 Requirements

* Multi-column sort
* Server/client filtering

### ⚠️ Edge Cases

* Large datasets

### 🚀 Performance

* Memoized sorting

***

## 9. 🧠 Global Toast Notification System

### 📌 Requirements

* Show multiple toasts
* Auto-dismiss

### 🏗️ Architecture

* Context API

***

## 10. 🔍 File Explorer (Tree View)

### 📌 Requirements

* Nested folders
* Expand/collapse

### ⚠️ Edge Cases

* Deep nesting

***

## 11. 🧩 Modal Manager System

### 📌 Requirements

* Multiple modals
* Stack management

***

## 12. 📊 Real-time Stock Dashboard

### 📌 Requirements

* Live updates
* Graph rendering

### ⚠️ Edge Cases

* Rapid updates

***

## 13. 🧠 Form Builder (Drag & Drop)

### 📌 Requirements

* Build forms dynamically

***

## 14. 🔁 Polling + Manual Refresh System

### 📌 Requirements

* Auto refresh every X sec
* Manual refresh

***

## 15. 📦 Shopping Cart with Optimistic Updates

### 📌 Requirements

* Instant UI update
* Rollback on failure

***

## 16. 🧠 Tabs with Lazy Loading

### 📌 Requirements

* Load content on demand

***

## 17. 🔍 Search + Highlight System

### 📌 Requirements

* Highlight matches in large text

***

## 18. 🔄 Component Visibility Tracker

### 📌 Requirements

* Detect if component in viewport

***

# 📌 What These Test

These problems simulate:

* **Real production UI systems**
* **State architecture decisions**
* **Performance bottlenecks**
* **Component composition skills**
* **Edge-case handling mindset**

***

# 🚀 If You Want Next Level

Below is a **FAANG-level interview set (20 questions)** on **React Components (Functional & Class Basics)**.
These emphasize **decision-making, internals, trade-offs, debugging, and performance awareness**.

***

# 🧠 Senior React Interview Questions — Components

***

## 1. When would you intentionally choose a Class Component over a Functional Component today?

### 🔍 Follow-up

* How would you implement error boundaries using functional components?
* What are the trade-offs?

### ✅ Strong Answer

* Primarily for **Error Boundaries** (until recently functional alternatives stabilized)
* Legacy systems where refactoring cost is high
* Class lifecycle sometimes clearer for debugging complex flows

```jsx theme={null}
class ErrorBoundary extends React.Component {
  componentDidCatch(error, info) {}
}
```

### ❌ Weak Answer

* “Class components are faster”
  👉 Incorrect — no inherent performance advantage

***

## 2. Explain how React keeps track of state in functional components internally.

### 🔍 Follow-up

* Why does hook order matter?

### ✅ Strong Answer

* React stores hooks in a **linked list tied to Fiber nodes**
* State is mapped by **call order**, not variable names

### ❌ Weak Answer

* “React tracks state by variable name”
  👉 Completely incorrect mental model

***

## 3. You see unnecessary re-renders in a deep component tree. How do you debug it?

### 🔍 Follow-up

* What tools and techniques do you use?

### ✅ Strong Answer

* Use React DevTools Profiler
* Identify prop changes (reference vs value)
* Check parent re-renders
* Apply memoization strategically

### ❌ Weak Answer

* “Just add React.memo everywhere”
  👉 Blind optimization → can worsen performance

***

## 4. Why does this cause a bug?

```jsx theme={null}
setCount(count + 1);
setCount(count + 1);
```

### 🔍 Follow-up

* How does batching affect this?

### ✅ Strong Answer

* Both updates use stale value
* React batches updates → final state incorrect

### ❌ Weak Answer

* “Because setState is async”
  👉 Incomplete explanation

***

## 5. How would you design a reusable component system for a large application?

### 🔍 Follow-up

* How do you prevent tight coupling?

### ✅ Strong Answer

* Use **composition over inheritance**
* Isolate concerns
* Use controlled props + slots pattern

### ❌ Weak Answer

* “Just break into smaller components”
  👉 Lacks architectural thinking

***

## 6. Explain a real-world bug caused by using index as key.

### 🔍 Follow-up

* When is it acceptable?

### ✅ Strong Answer

* Reordering lists → incorrect DOM reuse
* Example: form inputs shifting values

### ❌ Weak Answer

* “It’s only a performance issue”
  👉 It’s a correctness issue

***

## 7. How do closures impact React components?

### 🔍 Follow-up

* Give a real bug example

### ✅ Strong Answer

* Closures capture stale values
* Common in async callbacks, effects

### ❌ Weak Answer

* “Closures don’t matter in React”
  👉 Fundamental misunderstanding

***

## 8. What are the trade-offs of lifting state up?

### 🔍 Follow-up

* When does it become a problem?

### ✅ Strong Answer

* Enables shared state
* But leads to **prop drilling + unnecessary renders**

### ❌ Weak Answer

* “It’s always best practice”
  👉 Not scalable in large apps

***

## 9. Why is React.memo sometimes ineffective?

### 🔍 Follow-up

* How do you fix it?

### ✅ Strong Answer

* Fails with unstable references (objects/functions)

```jsx theme={null}
<Child data={{ a: 1 }} />
```

### ❌ Weak Answer

* “Because memo is buggy”
  👉 Misunderstanding of reference equality

***

## 10. Explain reconciliation and its assumptions.

### 🔍 Follow-up

* How do keys affect it?

### ✅ Strong Answer

* React uses **O(n) diffing heuristic**
* Assumes stable structure + keys

### ❌ Weak Answer

* “React compares everything deeply”
  👉 Incorrect

***

## 11. You have a component that fetches data. It sometimes shows outdated results. Why?

### 🔍 Follow-up

* How do you fix it?

### ✅ Strong Answer

* **Race condition**
* Older request resolves after newer one

### ❌ Weak Answer

* “API is slow”
  👉 Avoids root cause

***

## 12. How would you prevent unnecessary re-renders in a form-heavy UI?

### 🔍 Follow-up

* Controlled vs uncontrolled trade-offs?

### ✅ Strong Answer

* Split components
* Use local state
* Avoid global re-renders

### ❌ Weak Answer

* “Use Redux”
  👉 Doesn’t solve rendering issue

***

## 13. Why are hooks restricted to top-level calls?

### 🔍 Follow-up

* What breaks if violated?

### ✅ Strong Answer

* Hook order consistency required for state mapping

### ❌ Weak Answer

* “Just a React rule”
  👉 No understanding of internals

***

## 14. How do you handle expensive computations in components?

### 🔍 Follow-up

* When is useMemo harmful?

### ✅ Strong Answer

* Use `useMemo` when needed
* Avoid overuse (adds overhead)

### ❌ Weak Answer

* “Always use useMemo”
  👉 Premature optimization

***

## 15. Describe a scenario where a component should NOT re-render but does.

### 🔍 Follow-up

* How do you fix it?

### ✅ Strong Answer

* Caused by new prop references
* Fix via memoization or restructuring

***

## 16. What happens during render vs commit phases?

### 🔍 Follow-up

* Why is this important?

### ✅ Strong Answer

* Render = calculate changes (can be interrupted)
* Commit = apply changes (synchronous)

***

## 17. How do you design components for scalability?

### 🔍 Follow-up

* What anti-patterns do you avoid?

### ✅ Strong Answer

* Small, composable components
* Avoid monolith components

***

## 18. How would you debug a component that resets its state unexpectedly?

### 🔍 Follow-up

* What React concept is involved?

### ✅ Strong Answer

* Likely unmount/remount issue
* Caused by conditional rendering or key change

***

## 19. Explain controlled vs uncontrolled components in a large system.

### 🔍 Follow-up

* When do you mix both?

### ✅ Strong Answer

* Controlled = predictable
* Uncontrolled = performance-friendly

***

## 20. How do you decide component boundaries in a performance-critical app?

### 🔍 Follow-up

* What trade-offs do you consider?

### ✅ Strong Answer

* Balance between:

  * Reusability
  * Render isolation
  * Complexity

***

# 📌 Final Evaluation Criteria (What Interviewers Look For)

A strong candidate demonstrates:

* 🧠 **Mental model of React internals**
* ⚖️ **Trade-off awareness**
* 🐞 **Debugging mindset**
* 🚀 **Performance reasoning**
* 🏗️ **Component architecture thinking**

***
