> ## 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.

# Props

# 📘 React Props — Complete In-Depth Theory Guide

***

## 1. Introduction

### 🔹 What are Props?

**Props (short for “properties”)** are **inputs passed from a parent component to a child component** in React.

They allow components to be:

* **Dynamic**
* **Reusable**
* **Configurable**

👉 Props are **read-only** and cannot be modified by the receiving component.

***

### 🔹 Why Props are Important in React

Props are fundamental because they enable:

* **Component Reusability**

  * Same component, different data
* **Separation of Concerns**

  * Logic in parent, UI in child
* **Data Flow**

  * Enables **unidirectional data flow** (top → down)

***

### 🔹 When and Why We Use Props

Use props when:

* You want to **pass data** to child components
* You need to **customize UI behavior**
* You want to **share state across components**
* You are building **composable UI systems**

***

## 2. Concepts / Internal Workings

### 🔹 Unidirectional Data Flow

React follows a **one-way data flow**:

```
Parent → Child → Grandchild
```

* Props flow **down the component tree**
* Child cannot directly modify parent data

***

### 🔹 Props are Immutable

Props are **read-only objects**.

```js theme={null}
function Child(props) {
  props.name = "New Name"; // ❌ Not allowed
}
```

👉 React enforces immutability to:

* Prevent side effects
* Ensure predictable UI updates

***

### 🔹 How Props Work Internally

Under the hood:

1. React creates a **virtual DOM element**
2. Props are stored as an object inside it
3. During rendering:

   * React compares old vs new props (diffing)
   * Updates only what changed

```js theme={null}
<MyComponent name="John" />
```

Internally becomes:

```js theme={null}
{
  type: MyComponent,
  props: { name: "John" }
}
```

***

### 🔹 Props vs State

| Feature    | Props     | State                |
| ---------- | --------- | -------------------- |
| Ownership  | Parent    | Component itself     |
| Mutability | Immutable | Mutable              |
| Purpose    | Pass data | Manage internal data |

***

### 🔹 Relationship with Other React Features

* **Hooks (`useState`, `useEffect`)**

  * Props often trigger effects

* **Context API**

  * Alternative to passing props deeply (prop drilling)

* **Memoization (`React.memo`)**

  * Props are used for comparison to prevent re-renders

***

## 3. Syntax & Examples

***

### 🔹 Basic Props Passing

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

function App() {
  return <Greeting name="Alice" />;
}
```

***

### 🔹 Destructuring Props

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

***

### 🔹 Passing Multiple Props

```jsx theme={null}
function User({ name, age }) {
  return (
    <div>
      <p>{name}</p>
      <p>{age}</p>
    </div>
  );
}

<User name="John" age={25} />
```

***

### 🔹 Default Props

```jsx theme={null}
function Button({ text = "Click Me" }) {
  return <button>{text}</button>;
}
```

***

### 🔹 Passing Functions as Props

```jsx theme={null}
function Button({ onClick }) {
  return <button onClick={onClick}>Click</button>;
}

function App() {
  const handleClick = () => alert("Clicked!");

  return <Button onClick={handleClick} />;
}
```

👉 Enables **child → parent communication**

***

### 🔹 Passing Objects & Arrays

```jsx theme={null}
function Profile({ user }) {
  return <h2>{user.name}</h2>;
}

const user = { name: "Alice" };

<Profile user={user} />;
```

***

### 🔹 Children Prop

```jsx theme={null}
function Card({ children }) {
  return <div className="card">{children}</div>;
}

<Card>
  <h2>Title</h2>
  <p>Description</p>
</Card>
```

👉 `children` is a **special prop**

***

### 🔹 Spread Props

```jsx theme={null}
const props = { name: "John", age: 30 };

<User {...props} />
```

***

### 🔹 Conditional Props

```jsx theme={null}
<Button disabled={isLoading} />
```

***

### 🔹 Inline Expressions

```jsx theme={null}
<User age={20 + 5} />
```

***

## 4. Edge Cases / Common Mistakes

***

### ❌ Mutating Props

```jsx theme={null}
function Child(props) {
  props.value = 10; // ❌
}
```

✅ Fix: Use state or callbacks

***

### ❌ Prop Drilling

```jsx theme={null}
<App>
  <Parent>
    <Child>
      <GrandChild data={data} />
    </Child>
  </Parent>
</App>
```

👉 Problem: Passing props through many layers

✅ Solution:

* Context API
* State management (Redux, Zustand)

***

### ❌ Re-render Issues with Objects/Functions

```jsx theme={null}
<MyComponent obj={{ name: "John" }} />
```

👉 New object created every render → unnecessary re-renders

✅ Fix:

```jsx theme={null}
const obj = useMemo(() => ({ name: "John" }), []);
```

***

### ❌ Missing Props

```jsx theme={null}
function User({ name }) {
  return <p>{name.toUpperCase()}</p>;
}
```

👉 Crash if `name` is undefined

✅ Fix:

```jsx theme={null}
function User({ name = "" }) {
  return <p>{name.toUpperCase()}</p>;
}
```

***

### ❌ Incorrect Type Usage

Passing wrong types can break UI.

✅ Solution:

* Use TypeScript or PropTypes

***

### ❌ Overusing Props

Too many props → hard to maintain

```jsx theme={null}
<Component a b c d e f g />
```

✅ Fix:

* Group into objects
* Refactor components

***

## 5. Best Practices

***

### ✅ Keep Props Minimal

* Pass only what is needed
* Avoid unnecessary data

***

### ✅ Use Destructuring

```jsx theme={null}
function Card({ title, description }) {}
```

Improves readability

***

### ✅ Use Meaningful Names

```jsx theme={null}
<User isLoggedIn /> // ✅
<User flag />       // ❌
```

***

### ✅ Avoid Inline Functions (When Needed)

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

Better:

```jsx theme={null}
<Button onClick={handleClick} /> // ✅
```

***

### ✅ Memoization for Performance

Use:

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

To prevent unnecessary re-renders

***

### ✅ Validate Props

Using TypeScript:

```ts theme={null}
type Props = {
  name: string;
};
```

***

### ✅ Component Composition over Props Explosion

Instead of:

```jsx theme={null}
<Modal title="Title" content="Content" footer="Footer" />
```

Prefer:

```jsx theme={null}
<Modal>
  <Header />
  <Body />
  <Footer />
</Modal>
```

***

### ✅ Avoid Deep Prop Drilling

Use:

* Context API
* Global state management

***

### ✅ Keep Components Pure

Props in → UI out

```jsx theme={null}
function PureComponent({ value }) {
  return <div>{value}</div>;
}
```

***

## 🔚 Summary

Props are:

* **Immutable inputs**
* Used for **component communication**
* Key to **reusability and composition**

Mastering props helps you:

* Design scalable UI
* Optimize performance
* Write maintainable React code

***

# 📘 React Props — Senior-Level Conceptual Interview Questions

***

## 1. Why are props immutable in React? What would break if they were mutable?

### ✅ Strong Answer

Props are immutable to maintain **predictability and consistency in rendering**.

#### WHY:

* React relies on **pure component rendering**
* Immutability enables **efficient diffing (reconciliation)**
* Prevents **side effects across component boundaries**

If props were mutable:

* Child components could **silently modify parent data**
* React’s **Virtual DOM diffing would become unreliable**
* Debugging becomes extremely difficult due to **hidden mutations**

```jsx theme={null}
function Child({ user }) {
  user.name = "Hacked"; // ❌ breaks data integrity
}
```

#### Comparison:

* Props → Immutable (controlled externally)
* State → Mutable (controlled internally)

***

## 2. How does React detect prop changes during reconciliation?

### ✅ Strong Answer

React uses **shallow comparison** of props during reconciliation.

#### HOW:

* When a component re-renders:

  * React compares **previous props vs new props**
  * If different → re-render child

```jsx theme={null}
<MyComponent obj={{ name: "John" }} />
```

This creates a **new object reference each render**, so React sees it as changed.

#### WHY:

* Shallow comparison is **fast (O(n))**
* Deep comparison would be **expensive**

#### Optimization:

```jsx theme={null}
const obj = useMemo(() => ({ name: "John" }), []);
```

#### Alternative:

* `React.memo()` for functional components

***

## 3. Explain prop drilling. When is it actually acceptable?

### ✅ Strong Answer

**Prop drilling** is passing props through multiple intermediate components.

#### Problem:

* Intermediate components don’t use the data
* Leads to **tight coupling and poor maintainability**

#### When it's OK:

* Small component trees
* Clear ownership of data
* Avoids unnecessary abstraction

#### When NOT:

* Deep trees
* Frequently changing data

#### Alternatives:

* Context API
* State management libraries

```jsx theme={null}
<Parent>
  <Child>
    <GrandChild data={data} />
  </Child>
</Parent>
```

***

## 4. What are the trade-offs between props and Context API?

### ✅ Strong Answer

| Props               | Context                     |
| ------------------- | --------------------------- |
| Explicit            | Implicit                    |
| Easy to trace       | Harder to debug             |
| Good for local data | Good for global/shared data |

#### Trade-offs:

**Props**

* ✅ Transparent data flow
* ❌ Verbose (prop drilling)

**Context**

* ✅ Eliminates drilling
* ❌ Can cause unnecessary re-renders

#### Key Insight:

Context is not a replacement for props — it’s a **complement**

***

## 5. Why do inline objects/functions in props cause performance issues?

### ✅ Strong Answer

Because they create **new references on every render**.

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

React sees:

* Old function !== New function → triggers re-render

#### WHY:

* JavaScript compares objects/functions by reference

#### Fix:

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

#### When it matters:

* In memoized components (`React.memo`)

***

## 6. How do props enable inversion of control in React?

### ✅ Strong Answer

Props allow parent components to **control child behavior**.

#### Example:

```jsx theme={null}
function Button({ onClick }) {
  return <button onClick={onClick}>Click</button>;
}
```

Parent decides behavior:

```jsx theme={null}
<Button onClick={handleSubmit} />
```

#### WHY:

* Promotes **flexibility and reusability**
* Decouples logic from UI

#### Alternative:

* Hardcoding logic inside component → less reusable

***

## 7. What is the “children” prop and why is it powerful?

### ✅ Strong Answer

`children` allows components to act as **wrappers or layouts**.

```jsx theme={null}
<Card>
  <h1>Title</h1>
</Card>
```

#### WHY powerful:

* Enables **composition over configuration**
* Avoids prop explosion

#### Alternative:

```jsx theme={null}
<Card title="Title" content="..." /> // less flexible
```

***

## 8. How does React.memo interact with props?

### ✅ Strong Answer

`React.memo` prevents re-render if props haven’t changed (shallow comparison).

```jsx theme={null}
const MyComponent = React.memo(({ value }) => {
  return <div>{value}</div>;
});
```

#### Pitfall:

```jsx theme={null}
<MyComponent obj={{ a: 1 }} /> // always re-renders
```

#### WHY:

* New reference each render

#### Fix:

* Memoize props
* Use custom comparison function

***

## 9. What happens when props change? Describe the full lifecycle.

### ✅ Strong Answer

1. Parent re-renders
2. New props passed to child
3. React compares old vs new props
4. If changed:

   * Child re-renders
   * Effects may run (`useEffect`)

#### Important:

* Even if props are same → child may still re-render (unless memoized)

***

## 10. Can a component re-render without prop changes?

### ✅ Strong Answer

Yes.

#### Reasons:

* Parent re-render
* Internal state changes
* Context updates

```jsx theme={null}
function Parent() {
  const [count, setCount] = useState(0);
  return <Child name="John" />;
}
```

Child re-renders even if `name` didn’t change.

#### Optimization:

* `React.memo`

***

## 11. Why is passing large objects as props risky?

### ✅ Strong Answer

* Causes **frequent re-renders**
* Harder to track changes
* Breaks memoization

#### Better:

```jsx theme={null}
<User name={user.name} />
```

Instead of:

```jsx theme={null}
<User user={user} />
```

#### Trade-off:

* Granularity vs convenience

***

## 12. How do you handle optional props safely?

### ✅ Strong Answer

Use:

* Default values
* Type checking

```jsx theme={null}
function User({ name = "Guest" }) {
  return <p>{name}</p>;
}
```

#### WHY:

Prevents runtime errors:

```jsx theme={null}
name.toUpperCase() // crash if undefined
```

***

## 13. Explain controlled vs uncontrolled behavior using props.

### ✅ Strong Answer

**Controlled component:**

* Parent controls value via props

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

**Uncontrolled:**

* Component manages its own state

#### WHY:

* Controlled → predictable
* Uncontrolled → simpler but less control

***

## 14. What are the dangers of “prop explosion”?

### ✅ Strong Answer

Too many props:

```jsx theme={null}
<Component a b c d e f />
```

#### Problems:

* Hard to maintain
* Poor readability
* Tight coupling

#### Solutions:

* Group into objects
* Use composition

***

## 15. When should you derive state from props (and when not)?

### ✅ Strong Answer

#### Avoid:

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

#### WHY:

* Leads to **stale state**
* Sync issues

#### Use only when:

* Need to **transform props once**

#### Alternative:

* Compute directly from props
* Use memoization

***

## 16. How do props interact with hooks like useEffect?

### ✅ Strong Answer

Props can trigger effects:

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

#### WHY:

* Dependency array watches prop changes

#### Pitfall:

* Missing dependency → stale data
* Over-dependency → unnecessary calls

***

## 17. What is a render prop pattern and how does it differ from normal props?

### ✅ Strong Answer

A **render prop** is a function prop that returns JSX.

```jsx theme={null}
<DataFetcher render={(data) => <UI data={data} />} />
```

#### WHY:

* Enables **dynamic rendering logic**

#### vs Normal Props:

* Normal → static data
* Render prop → dynamic UI logic

***

## 18. How would you design a highly reusable component using props?

### ✅ Strong Answer

Principles:

* Keep props minimal
* Use `children`
* Accept behavior via callbacks

```jsx theme={null}
function Modal({ isOpen, onClose, children }) {
  if (!isOpen) return null;
  return <div onClick={onClose}>{children}</div>;
}
```

#### WHY:

* Flexible
* Composable
* Decoupled

***

## 🔚 Final Takeaway

Senior-level understanding of props is about:

* **Data flow architecture**
* **Performance implications**
* **Component design philosophy**
* **Trade-offs between abstraction vs simplicity**

***

# 📘 React Props — Senior-Level MCQs (Deep Understanding)

***

## 1. What happens in the following scenario?

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

function Parent() {
  const data = { value: 1 };
  return <Child data={data} />;
}
```

### Options:

A. Child renders only once
B. Child re-renders on every Parent render
C. Child never re-renders
D. React throws an error

### ✅ Correct Answer: B

### ✔ Explanation:

* A **new object** is created on every render → new reference
* React sees `data` as changed → triggers re-render

### ❌ Why others are wrong:

* A: Incorrect — reference changes every time
* C: Impossible unless memoized
* D: No error here

***

## 2. What will prevent unnecessary re-renders here?

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

### Options:

A. Wrap Child with `React.memo` only
B. Use `useMemo` for config
C. Use `useCallback`
D. Nothing can prevent it

### ✅ Correct Answer: B

### ✔ Explanation:

* Object literal creates new reference
* `useMemo` stabilizes it

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

### ❌ Why others are wrong:

* A: Won’t help alone (props still change)
* C: For functions, not objects
* D: Incorrect — optimization exists

***

## 3. What happens if props are mutated inside a child?

```jsx theme={null}
function Child(props) {
  props.count = 10;
}
```

### Options:

A. React prevents mutation automatically
B. Parent state updates
C. Silent mutation causing bugs
D. Component crashes

### ✅ Correct Answer: C

### ✔ Explanation:

* JS allows mutation → React doesn’t block it
* Leads to **unexpected side effects**

### ❌ Why others are wrong:

* A: No enforcement at runtime
* B: No automatic sync
* D: No crash unless used incorrectly

***

## 4. Why does this component re-render?

```jsx theme={null}
const Child = React.memo(({ onClick }) => {
  console.log("Render");
  return <button onClick={onClick}>Click</button>;
});

<Child onClick={() => console.log("Hi")} />
```

### Options:

A. React.memo doesn’t work with functions
B. Function is recreated each render
C. Event handlers always trigger re-render
D. Memo only works with state

### ✅ Correct Answer: B

### ✔ Explanation:

* New function reference each render → fails shallow comparison

### ❌ Why others are wrong:

* A: Memo works fine with functions
* C: Events don’t trigger re-render by default
* D: Memo works with props

***

## 5. What is the best fix?

### Options:

A. Move function outside component
B. Use `useCallback`
C. Use `useEffect`
D. No fix needed

### ✅ Correct Answer: B

### ✔ Explanation:

```jsx theme={null}
const handleClick = useCallback(() => {
  console.log("Hi");
}, []);
```

### ❌ Why others are wrong:

* A: May break access to state
* C: Irrelevant
* D: Incorrect

***

## 6. What will happen?

```jsx theme={null}
function Child({ user }) {
  return <p>{user.name}</p>;
}

<Child />
```

### Options:

A. Renders empty
B. Throws runtime error
C. React warns but works
D. React auto-fills props

### ✅ Correct Answer: B

### ✔ Explanation:

* `user` is undefined → `user.name` crashes

### ❌ Why others are wrong:

* A: No fallback
* C: No automatic handling
* D: React doesn’t infer props

***

## 7. What is the best fix?

### Options:

A. Optional chaining
B. Default props
C. Both A and B
D. Wrap in try-catch

### ✅ Correct Answer: C

### ✔ Explanation:

```jsx theme={null}
function Child({ user = {} }) {
  return <p>{user?.name}</p>;
}
```

### ❌ Why others are wrong:

* A/B alone may not fully cover
* D: Overkill

***

## 8. What is the issue here?

```jsx theme={null}
function Parent() {
  const [count, setCount] = useState(0);
  return <Child value={count} />;
}
```

### Options:

A. Child won’t update
B. Child always re-renders
C. Props cause memory leak
D. Infinite loop

### ✅ Correct Answer: B

### ✔ Explanation:

* Parent state change → re-render → child re-renders

### ❌ Why others are wrong:

* A: Incorrect
* C/D: Not applicable

***

## 9. How to optimize the child?

### Options:

A. React.memo
B. useEffect
C. useReducer
D. useRef

### ✅ Correct Answer: A

***

## 10. What happens with prop drilling?

### Options:

A. Improves performance
B. Increases coupling
C. Reduces bugs
D. Avoids re-renders

### ✅ Correct Answer: B

### ✔ Explanation:

* Intermediate components depend on props unnecessarily

***

## 11. Which is better for deeply nested data?

### Options:

A. Props
B. Context API
C. Inline functions
D. useEffect

### ✅ Correct Answer: B

***

## 12. What happens here?

```jsx theme={null}
const Child = React.memo(({ data }) => {
  console.log("Render");
  return null;
});

const data = { a: 1 };

<Child data={data} />
```

### Options:

A. Always re-renders
B. Never re-renders
C. Re-renders only if reference changes
D. Crashes

### ✅ Correct Answer: C

***

## 13. What is wrong with this pattern?

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

### Options:

A. Nothing
B. Causes stale state issues
C. Causes infinite loop
D. Slows rendering

### ✅ Correct Answer: B

### ✔ Explanation:

* State won’t update if prop changes

***

## 14. What is the better approach?

### Options:

A. useEffect sync
B. Derive directly from props
C. Global state
D. Ignore updates

### ✅ Correct Answer: B

***

## 15. Why is `children` preferred over multiple props?

### Options:

A. Faster rendering
B. Avoids prop explosion
C. Required by React
D. Works only in class components

### ✅ Correct Answer: B

***

## 16. What happens here?

```jsx theme={null}
<Child key="1" value={10} />
```

Then:

```jsx theme={null}
<Child key="2" value={10} />
```

### Options:

A. Props update only
B. Component remounts
C. No change
D. Error

### ✅ Correct Answer: B

### ✔ Explanation:

* Key change → React treats as new component

***

## 17. Which causes unnecessary re-renders?

### Options:

A. Stable primitive props
B. Inline objects/functions
C. useMemo values
D. Static props

### ✅ Correct Answer: B

***

## 18. What is the main purpose of props?

### Options:

A. Manage internal state
B. Enable data flow and composition
C. Replace hooks
D. Optimize rendering

### ✅ Correct Answer: B

***

## 🔚 Final Insight

These questions test:

* Reference equality vs value equality
* Rendering behavior
* Component design decisions
* Performance optimization

***

# 📘 React Props — Real-World Coding Problems (Senior Level)

***

## 🧩 Problem 1: Dynamic Profile Card System

### 📌 Problem Statement

Build a reusable `ProfileCard` component that receives user data via props and renders different layouts based on user type.

### 🔒 Constraints

* Props: `{ user, variant }`
* `variant` can be `"compact"` or `"detailed"`
* Must not mutate props

### ✅ Expected Behavior

* Compact → name + avatar
* Detailed → name + avatar + bio + stats

### ⚠️ Edge Cases

* Missing user fields
* Unknown variant

### 💡 Solution

```jsx theme={null}
function ProfileCard({ user = {}, variant = "compact" }) {
  if (variant === "detailed") {
    return (
      <div>
        <img src={user.avatar} />
        <h2>{user.name}</h2>
        <p>{user.bio}</p>
      </div>
    );
  }
  return <h2>{user.name}</h2>;
}
```

### 🧠 Explanation

* Uses **default props** to avoid crashes
* Conditional rendering based on props

***

## 🧩 Problem 2: Controlled Form Input Wrapper

### 📌 Problem Statement

Create an `InputField` component that behaves as a controlled component via props.

### 🔒 Constraints

* Props: `{ value, onChange }`
* Must not manage internal state

### ✅ Expected Behavior

* Value updates only via parent

### ⚠️ Edge Cases

* Undefined value
* onChange not passed

### 💡 Solution

```jsx theme={null}
function InputField({ value = "", onChange }) {
  return <input value={value} onChange={onChange} />;
}
```

### 🧠 Explanation

* Demonstrates **controlled component via props**

***

## 🧩 Problem 3: Prevent Unnecessary Re-renders

### 📌 Problem Statement

Optimize a `ListItem` component receiving object props.

### 🔒 Constraints

* Must avoid unnecessary re-renders

### ⚠️ Edge Cases

* Parent re-renders frequently

### 💡 Solution

```jsx theme={null}
const ListItem = React.memo(({ item }) => {
  return <li>{item.name}</li>;
});
```

Parent:

```jsx theme={null}
const item = useMemo(() => ({ name: "Item" }), []);
<ListItem item={item} />;
```

### 🧠 Explanation

* Combines **React.memo + stable props**

***

## 🧩 Problem 4: Modal with Render Props

### 📌 Problem Statement

Build a modal that receives UI via a render prop.

### 🔒 Constraints

* Props: `{ render }`

### 💡 Solution

```jsx theme={null}
function Modal({ render }) {
  return <div className="modal">{render()}</div>;
}
```

Usage:

```jsx theme={null}
<Modal render={() => <p>Hello</p>} />
```

### 🧠 Explanation

* Demonstrates **render prop pattern**

***

## 🧩 Problem 5: Button with Behavior Injection

### 📌 Problem Statement

Create a reusable button that receives behavior via props.

### 💡 Solution

```jsx theme={null}
function Button({ onClick, children }) {
  return <button onClick={onClick}>{children}</button>;
}
```

### 🧠 Explanation

* Shows **inversion of control**

***

## 🧩 Problem 6: Deep Prop Drilling Refactor

### 📌 Problem Statement

Refactor a deeply nested component passing props through 4 levels.

### 🔒 Constraints

* Avoid prop drilling

### 💡 Solution

Use Context:

```jsx theme={null}
const DataContext = React.createContext();

<DataContext.Provider value={data}>
  <DeepChild />
</DataContext.Provider>
```

### 🧠 Explanation

* Avoids unnecessary prop passing

***

## 🧩 Problem 7: Derived State Anti-pattern Fix

### 📌 Problem Statement

Fix component syncing state from props incorrectly.

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

### 💡 Solution

```jsx theme={null}
function Component({ value }) {
  return <div>{value}</div>;
}
```

### 🧠 Explanation

* Avoids **stale state issues**

***

## 🧩 Problem 8: Safe Optional Props Rendering

### 📌 Problem Statement

Render optional nested data safely.

### 💡 Solution

```jsx theme={null}
function User({ user }) {
  return <p>{user?.profile?.name || "Guest"}</p>;
}
```

***

## 🧩 Problem 9: Generic Table Component

### 📌 Problem Statement

Build a table that receives columns and data via props.

### 🔒 Constraints

* Dynamic columns

### 💡 Solution

```jsx theme={null}
function Table({ data, columns }) {
  return (
    <table>
      <thead>
        <tr>
          {columns.map(col => <th key={col}>{col}</th>)}
        </tr>
      </thead>
      <tbody>
        {data.map((row, i) => (
          <tr key={i}>
            {columns.map(col => <td key={col}>{row[col]}</td>)}
          </tr>
        ))}
      </tbody>
    </table>
  );
}
```

***

## 🧩 Problem 10: Prevent Function Prop Re-Creation

### 📌 Problem Statement

Optimize function props in a list.

### 💡 Solution

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

***

## 🧩 Problem 11: Compound Component Pattern

### 📌 Problem Statement

Create a `Tabs` system using props + children.

### 💡 Solution

```jsx theme={null}
function Tabs({ children }) {
  return <div>{children}</div>;
}
```

***

## 🧩 Problem 12: Prop Validation with TypeScript

### 📌 Problem Statement

Ensure correct prop types.

### 💡 Solution

```ts theme={null}
type Props = {
  name: string;
};
```

***

## 🧩 Problem 13: Conditional Rendering Based on Props

### 📌 Problem Statement

Render loading or content.

### 💡 Solution

```jsx theme={null}
function Loader({ isLoading, children }) {
  return isLoading ? <p>Loading...</p> : children;
}
```

***

## 🧩 Problem 14: Reusable Layout Wrapper

### 📌 Problem Statement

Create layout using children.

### 💡 Solution

```jsx theme={null}
function Layout({ header, children, footer }) {
  return (
    <>
      {header}
      {children}
      {footer}
    </>
  );
}
```

***

## 🧩 Problem 15: Key Prop Behavior

### 📌 Problem Statement

Explain remount behavior when key changes.

### 💡 Explanation

* Changing `key` forces remount → resets state

***

## 🧩 Problem 16: Memoization Pitfall

### 📌 Problem Statement

Fix unnecessary re-renders with nested props.

### 💡 Solution

* Normalize props
* Avoid passing full objects

***

## 🧩 Problem 17: Dynamic Theme Injection

### 📌 Problem Statement

Pass theme via props.

### 💡 Solution

```jsx theme={null}
function Box({ theme }) {
  return <div style={{ color: theme.color }} />;
}
```

***

## 🧩 Problem 18: Higher-Order Component with Props

### 📌 Problem Statement

Wrap component and pass extra props.

### 💡 Solution

```jsx theme={null}
function withUser(Component) {
  return function Wrapped(props) {
    return <Component {...props} user={{ name: "John" }} />;
  };
}
```

***

## 🧩 Problem 19: Prop Normalization Layer

### 📌 Problem Statement

Normalize inconsistent API response props.

### 💡 Solution

```jsx theme={null}
const normalizedUser = {
  name: user.name || user.username
};
```

***

## 🧩 Problem 20: Performance Audit Scenario

### 📌 Problem Statement

Optimize a large list receiving props.

### 💡 Solution

* Use `React.memo`
* Virtualization (React Window)
* Stable props

***

# 🔚 Final Takeaway

These problems test:

* Real-world prop usage
* Performance optimization
* Architecture decisions
* Debugging mindset

***

# 🛠️ React Props — Senior-Level Debugging Challenges (Production Scenarios)

***

## 🧩 1. Infinite Re-render due to Derived State

### ❌ Buggy Code

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

  useEffect(() => {
    setCount(value);
  }, [count]); // ❌ wrong dependency

  return <p>{count}</p>;
}
```

### 🔍 What’s Wrong

* Effect depends on `count` but sets `count` → infinite loop

### ❓ WHY it happens

* Changing `count` triggers effect again → loop

### ✅ Fix

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

### 🧠 Best Practice

* Avoid syncing props to state unless necessary

***

## 🧩 2. React.memo Not Working

### ❌ Buggy Code

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

function Parent() {
  return <Child config={{ theme: "dark" }} />;
}
```

### 🔍 What’s Wrong

* Inline object causes new reference each render

### ❓ WHY

* Shallow comparison fails

### ✅ Fix

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

### 🧠 Best Practice

* Stabilize object/array props

***

## 🧩 3. Unexpected Undefined Crash

### ❌ Buggy Code

```jsx theme={null}
function Profile({ user }) {
  return <p>{user.name.toUpperCase()}</p>;
}
```

### 🔍 What’s Wrong

* `user` may be undefined

### ❓ WHY

* Props not guaranteed unless validated

### ✅ Fix

```jsx theme={null}
function Profile({ user = {} }) {
  return <p>{user.name?.toUpperCase() || "Guest"}</p>;
}
```

### 🧠 Best Practice

* Always guard optional props

***

## 🧩 4. Function Prop Causing Re-renders

### ❌ Buggy Code

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

### 🔍 What’s Wrong

* New function every render

### ❓ WHY

* Breaks memoization

### ✅ Fix

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

### 🧠 Best Practice

* Use `useCallback` for stable handlers

***

## 🧩 5. Prop Mutation Bug

### ❌ Buggy Code

```jsx theme={null}
function Child({ items }) {
  items.push("new"); // ❌ mutation
  return <div>{items.length}</div>;
}
```

### 🔍 What’s Wrong

* Mutating props

### ❓ WHY

* Breaks React’s data flow

### ✅ Fix

```jsx theme={null}
const newItems = [...items, "new"];
```

### 🧠 Best Practice

* Treat props as immutable

***

## 🧩 6. Stale Closure with Props

### ❌ Buggy Code

```jsx theme={null}
function Timer({ delay }) {
  useEffect(() => {
    const id = setInterval(() => {
      console.log(delay);
    }, 1000);
    return () => clearInterval(id);
  }, []); // ❌ missing dependency
}
```

### 🔍 What’s Wrong

* `delay` is stale

### ❓ WHY

* Closure captures initial value

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  const id = setInterval(() => {
    console.log(delay);
  }, delay);
  return () => clearInterval(id);
}, [delay]);
```

### 🧠 Best Practice

* Always include props in dependencies

***

## 🧩 7. Over-rendering Child Components

### ❌ Buggy Code

```jsx theme={null}
function Parent({ user }) {
  return <Child user={user} />;
}
```

Parent re-renders frequently.

### 🔍 Issue

* Child re-renders unnecessarily

### ❓ WHY

* No memoization

### ✅ Fix

```jsx theme={null}
const Child = React.memo(({ user }) => { ... });
```

### 🧠 Best Practice

* Memoize pure components

***

## 🧩 8. Incorrect Key Causing State Reset

### ❌ Buggy Code

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

### 🔍 What’s Wrong

* Index as key

### ❓ WHY

* Order changes → wrong reconciliation

### ✅ Fix

```jsx theme={null}
key={item.id}
```

### 🧠 Best Practice

* Use stable unique keys

***

## 🧩 9. Conditional Props Breaking UI

### ❌ Buggy Code

```jsx theme={null}
<Button disabled={isLoading && "true"} />
```

### 🔍 What’s Wrong

* Passing string instead of boolean

### ❓ WHY

* `"true"` is truthy but incorrect type

### ✅ Fix

```jsx theme={null}
disabled={isLoading}
```

***

## 🧩 10. Spreading Unnecessary Props

### ❌ Buggy Code

```jsx theme={null}
<Component {...props} />
```

### 🔍 Issue

* Passing unused props

### ❓ WHY

* Increases coupling, risk of bugs

### ✅ Fix

```jsx theme={null}
<Component name={props.name} />
```

***

## 🧩 11. Breaking Controlled Component

### ❌ Buggy Code

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

### 🔍 Issue

* Missing onChange

### ❓ WHY

* Becomes read-only

### ✅ Fix

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

***

## 🧩 12. Recomputing Expensive Props

### ❌ Buggy Code

```jsx theme={null}
<Chart data={processData(rawData)} />
```

### 🔍 Issue

* Expensive computation every render

### ❓ WHY

* Function runs each render

### ✅ Fix

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

***

## 🧩 13. Nested Object Prop Issue

### ❌ Buggy Code

```jsx theme={null}
<User settings={{ theme: { color: "blue" } }} />
```

### 🔍 Issue

* Deep object recreated

### ❓ WHY

* Breaks memo

### ✅ Fix

* Lift and memoize object

***

## 🧩 14. Children Misuse

### ❌ Buggy Code

```jsx theme={null}
function Wrapper({ children }) {
  children = <div>{children}</div>; // ❌ mutation
}
```

### 🔍 Issue

* Reassigning props

### ✅ Fix

```jsx theme={null}
return <div>{children}</div>;
```

***

## 🧩 15. Props Not Updating in Child

### ❌ Buggy Code

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

### 🔍 Issue

* Not synced with prop changes

### ✅ Fix

* Use props directly OR sync via effect

***

## 🧩 16. Boolean Prop Misinterpretation

### ❌ Buggy Code

```jsx theme={null}
<MyComponent isActive="false" />
```

### 🔍 Issue

* String is truthy

### ✅ Fix

```jsx theme={null}
isActive={false}
```

***

## 🧩 17. Overusing Props Instead of Composition

### ❌ Buggy Code

```jsx theme={null}
<Card title="..." content="..." footer="..." />
```

### 🔍 Issue

* Rigid API

### ✅ Fix

```jsx theme={null}
<Card>
  <Header />
  <Body />
</Card>
```

***

## 🧩 18. Missing Dependency Causing Buggy UI

### ❌ Buggy Code

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

### 🔍 Issue

* Doesn’t react to prop change

### ✅ Fix

```jsx theme={null}
[id]
```

***

## 🔚 Final Takeaway

These bugs reflect **real production issues**:

* Reference equality pitfalls
* Stale closures
* Improper memoization
* Incorrect assumptions about props

***

# 🏗️ React Props — Real-World Machine Coding Problems (Senior / Architect Level)

These are **production-grade problems** designed to test:

* Component architecture
* Data flow via props
* Performance & scalability
* Real-world trade-offs

***

## 🧩 1. Configurable Data Table (Enterprise Grid)

### 📌 Requirements

* Render dynamic table using props:

  * `columns`, `data`, `renderCell`, `sortConfig`
* Support:

  * Sorting
  * Custom cell rendering
  * Column visibility toggle

### 🖥️ UI Behavior

* Click column header → sort
* Toggle columns → hide/show instantly

### 🔄 Data Flow

* Parent owns data & sorting state
* Table receives everything via props

### ⚠️ Edge Cases

* Empty data
* Missing keys
* Large datasets

### ⚡ Performance

* Virtualization (react-window)
* Memoized rows

### 🏗️ Architecture

* `Table`
* `TableRow`
* `TableCell`

### 🧠 Approach

1. Normalize columns
2. Pass render functions as props
3. Memoize rows

***

## 🧩 2. Headless Modal System

### 📌 Requirements

* Build a modal with:

  * `isOpen`, `onClose`, `children`
* No styling (headless)

### 🖥️ UI Behavior

* Close on overlay click / ESC

### 🔄 Data Flow

* Parent controls open/close

### ⚠️ Edge Cases

* Multiple modals
* Focus trap

### ⚡ Performance

* Lazy mount/unmount

### 🏗️ Architecture

* `Modal`
* `Portal`

### 🧠 Approach

* Use `children` for flexibility
* Use props for behavior injection

***

## 🧩 3. Multi-Step Form Wizard

### 📌 Requirements

* Steps passed as props:

  * `steps`, `currentStep`, `onNext`, `onBack`

### 🖥️ UI Behavior

* Navigate steps
* Validate before next

### 🔄 Data Flow

* Central form state in parent

### ⚠️ Edge Cases

* Skip steps
* Validation errors

### ⚡ Performance

* Avoid re-rendering all steps

### 🏗️ Architecture

* `Wizard`
* `Step`

### 🧠 Approach

* Render active step only
* Pass handlers via props

***

## 🧩 4. Reusable Dropdown with Custom Rendering

### 📌 Requirements

* Props:

  * `options`, `renderOption`, `onSelect`

### 🖥️ UI Behavior

* Keyboard navigation
* Custom UI per option

### ⚠️ Edge Cases

* Empty list
* Duplicate values

### ⚡ Performance

* Debounced filtering

### 🧠 Approach

* Render prop for flexibility

***

## 🧩 5. Infinite Scroll Feed

### 📌 Requirements

* Props:

  * `fetchData`, `renderItem`

### 🖥️ UI Behavior

* Load more on scroll

### 🔄 Data Flow

* Parent handles API

### ⚠️ Edge Cases

* Duplicate fetch
* End of list

### ⚡ Performance

* Intersection Observer

### 🧠 Approach

* Controlled via props

***

## 🧩 6. Theme System (Dynamic Styling)

### 📌 Requirements

* Pass theme via props
* Support light/dark

### ⚠️ Edge Cases

* Missing theme keys

### ⚡ Performance

* Memoize theme object

### 🧠 Approach

* Theme provider or prop drilling trade-off

***

## 🧩 7. Form Builder (Schema-driven UI)

### 📌 Requirements

* Props:

  * `schema`, `onSubmit`

### 🖥️ UI Behavior

* Dynamically render inputs

### ⚠️ Edge Cases

* Unknown field types

### ⚡ Performance

* Lazy render sections

### 🧠 Approach

* Map schema → components

***

## 🧩 8. Drag & Drop List

### 📌 Requirements

* Props:

  * `items`, `onReorder`

### ⚠️ Edge Cases

* Rapid drag events

### ⚡ Performance

* Avoid full list re-render

### 🧠 Approach

* Stable keys
* Memoized items

***

## 🧩 9. Notification System

### 📌 Requirements

* Props:

  * `notifications`, `onDismiss`

### 🖥️ UI Behavior

* Auto-dismiss

### ⚠️ Edge Cases

* Duplicate notifications

### 🧠 Approach

* Controlled list via props

***

## 🧩 10. Search with Debounced Input

### 📌 Requirements

* Props:

  * `onSearch`

### ⚡ Performance

* Debounce input

***

## 🧩 11. Reusable Card System (Composable UI)

### 📌 Requirements

* Use `children` for layout slots

### 🧠 Approach

* Composition over props explosion

***

## 🧩 12. Chart Wrapper (Reusable Visualization)

### 📌 Requirements

* Props:

  * `data`, `config`

### ⚠️ Edge Cases

* Empty dataset

### ⚡ Performance

* Memoized transformations

***

## 🧩 13. Permission-based Rendering

### 📌 Requirements

* Props:

  * `permissions`, `children`

### 🧠 Approach

```jsx theme={null}
if (!permissions.includes("admin")) return null;
```

***

## 🧩 14. Lazy Image Component

### 📌 Requirements

* Props:

  * `src`, `placeholder`

### ⚡ Performance

* Intersection Observer

***

## 🧩 15. File Upload Component

### 📌 Requirements

* Props:

  * `onUpload`, `accept`

### ⚠️ Edge Cases

* Invalid file types

***

## 🧩 16. Pagination Component

### 📌 Requirements

* Props:

  * `page`, `totalPages`, `onChange`

***

## 🧩 17. Headless Tooltip System

### 📌 Requirements

* Props:

  * `content`, `children`

***

## 🧩 18. Virtualized List

### 📌 Requirements

* Props:

  * `items`, `rowHeight`

### ⚡ Performance

* Render visible rows only

***

## 🧩 19. Undo/Redo System

### 📌 Requirements

* Props:

  * `state`, `onUndo`, `onRedo`

***

## 🧩 20. Live Collaborative Cursor Tracker

### 📌 Requirements

* Props:

  * `users`, `positions`

### ⚠️ Edge Cases

* Rapid updates

### ⚡ Performance

* Throttle updates

***

# 🔚 Final Architect Insight

These problems test:

* **Prop-driven architecture**
* **Component composition vs configuration**
* **Performance tuning**
* **Scalable design patterns**

***

# 📘 React Props — FAANG-Level Interview Questions (Senior Depth)

***

## 1. How would you design a component API using props for long-term scalability?

### 🔁 Follow-up

* How do you prevent prop explosion?
* When would you switch to composition?

### ✅ Strong Answer

* Start with **minimal, explicit props**
* Prefer **composition (`children`) over configuration**
* Group related props into objects when needed
* Design for **extensibility without breaking changes**

```jsx theme={null}
<Modal>
  <Header />
  <Body />
</Modal>
```

#### WHY:

* Reduces coupling
* Improves flexibility

### ❌ Weak Answer

* “Just add more props as needed”
  👉 Fails because it ignores scalability and API design

***

## 2. Explain how React decides whether to re-render a component based on props.

### 🔁 Follow-up

* How does `React.memo` change this?
* What are its limitations?

### ✅ Strong Answer

* By default, React re-renders when parent renders
* `React.memo` does **shallow comparison of props**

#### Key Insight:

* Reference equality matters

### ❌ Weak Answer

* “React only re-renders when props change”
  👉 Incorrect — parent re-render triggers child too

***

## 3. You notice a component re-rendering frequently despite unchanged data. How do you debug it?

### 🔁 Follow-up

* What tools would you use?

### ✅ Strong Answer

* Check:

  * Inline objects/functions
  * Parent re-renders
  * Missing memoization
* Use:

  * React DevTools Profiler

### ❌ Weak Answer

* “Add React.memo everywhere”
  👉 Over-optimization without understanding cause

***

## 4. When would you avoid passing an object as a prop?

### 🔁 Follow-up

* When is it acceptable?

### ✅ Strong Answer

* Avoid when:

  * Object recreated each render
  * Component is memoized

* Acceptable when:

  * Stable reference (`useMemo`)
  * Small apps

### ❌ Weak Answer

* “Objects are always bad”
  👉 Oversimplification

***

## 5. Design a reusable table component. What props would you expose?

### 🔁 Follow-up

* How do you support custom rendering?

### ✅ Strong Answer

* Props:

  * `data`, `columns`, `renderCell`
* Use render props for flexibility

### ❌ Weak Answer

* “Just pass data and map it”
  👉 Not scalable or flexible

***

## 6. How do you handle deeply nested data without prop drilling?

### 🔁 Follow-up

* Trade-offs of Context API?

### ✅ Strong Answer

* Use Context for global/shared data
* Avoid overuse (causes re-renders)

### ❌ Weak Answer

* “Always use Context”
  👉 Ignores trade-offs

***

## 7. What are the risks of syncing props to state?

### 🔁 Follow-up

* When is it justified?

### ✅ Strong Answer

* Risks:

  * Stale state
  * Sync bugs

* Use only for:

  * Derived/controlled transformations

### ❌ Weak Answer

* “It’s fine to copy props into state”
  👉 Leads to bugs

***

## 8. How would you design a component that allows behavior injection?

### 🔁 Follow-up

* Compare with HOCs

### ✅ Strong Answer

* Use function props (callbacks)

```jsx theme={null}
<Button onClick={handleClick} />
```

### ❌ Weak Answer

* “Hardcode logic”
  👉 Not reusable

***

## 9. Why does this cause unnecessary re-renders?

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

### 🔁 Follow-up

* How do you fix it?

### ✅ Strong Answer

* New object reference each render

Fix:

```jsx theme={null}
useMemo(() => ({ theme: "dark" }), [])
```

### ❌ Weak Answer

* “React is inefficient”
  👉 Misunderstanding core behavior

***

## 10. How do you decide between props vs global state?

### 🔁 Follow-up

* What are scaling concerns?

### ✅ Strong Answer

* Props:

  * Local, predictable

* Global state:

  * Shared, complex

### ❌ Weak Answer

* “Use Redux for everything”
  👉 Overengineering

***

## 11. What is the role of `children` in API design?

### 🔁 Follow-up

* When not to use it?

### ✅ Strong Answer

* Enables composition
* Avoids rigid APIs

### ❌ Weak Answer

* “It’s just for nesting”
  👉 Misses design importance

***

## 12. A component is slow due to heavy prop computation. How do you optimize?

### 🔁 Follow-up

* Trade-offs of memoization?

### ✅ Strong Answer

* Use `useMemo`
* Move computation outside render

### ❌ Weak Answer

* “Use useEffect”
  👉 Wrong tool

***

## 13. Explain how prop changes trigger effects.

### 🔁 Follow-up

* What if dependency is missing?

### ✅ Strong Answer

* `useEffect` runs when dependencies change

### ❌ Weak Answer

* “Effects run on every render”
  👉 Incorrect

***

## 14. How would you design a headless component using props?

### 🔁 Follow-up

* Why is this pattern useful?

### ✅ Strong Answer

* Logic via props, UI via children

### ❌ Weak Answer

* “Just build UI directly”
  👉 Not reusable

***

## 15. How do you prevent unnecessary prop spreading?

### 🔁 Follow-up

* When is spreading useful?

### ✅ Strong Answer

* Explicit props preferred
* Spread only for wrappers

### ❌ Weak Answer

* “Always use spread”
  👉 Risky

***

## 16. What happens when a key changes but props don’t?

### 🔁 Follow-up

* Real-world use case?

### ✅ Strong Answer

* Component remounts → state reset

### ❌ Weak Answer

* “Nothing changes”
  👉 Incorrect

***

## 17. How do you handle optional props in large systems?

### 🔁 Follow-up

* Type safety strategies?

### ✅ Strong Answer

* Default values
* TypeScript

### ❌ Weak Answer

* “Just check manually”
  👉 Not scalable

***

## 18. Describe a real-world bug caused by props and how you’d fix it.

### 🔁 Follow-up

* How to prevent it?

### ✅ Strong Answer

* Example:

  * Inline object → re-render loop
* Fix:

  * Memoization

### ❌ Weak Answer

* “I’d debug in console”
  👉 Lacks depth

***

## 19. How would you audit a large app for prop-related performance issues?

### 🔁 Follow-up

* Metrics you’d track?

### ✅ Strong Answer

* Use Profiler
* Check:

  * Re-render frequency
  * Prop stability

### ❌ Weak Answer

* “Rewrite everything”
  👉 Unrealistic

***

## 🔚 Final Interview Insight

At FAANG level, props questions test:

* **Architectural thinking**
* **Trade-offs (simplicity vs scalability)**
* **Performance awareness**
* **Debugging intuition**

***
