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

# Higher-order components

# 📘 Higher-Order Components (HOC) in React — Complete Theory Guide

***

## 1. 📌 Introduction

### 🔹 What are Higher-Order Components (HOCs)?

A **Higher-Order Component (HOC)** is a function that:

* Takes a component as input
* Returns a **new enhanced component**

👉 In simple terms:

> HOC = function that wraps a component to add extra behavior

```js theme={null}
const EnhancedComponent = withFeature(WrappedComponent);
```

***

### 🔹 Why are HOCs Important?

Before hooks, HOCs were the primary way to:

* Reuse **stateful logic**
* Abstract cross-cutting concerns
* Avoid duplicating logic across components

They help:

* Keep components **clean and focused**
* Separate **logic from UI**

***

### 🔹 When and Why Do We Use It?

Use HOCs when:

* 🔁 Logic needs to be reused across components
* 🧠 You want to inject behavior (auth, logging, data fetching)
* 🧩 You want to enhance components without modifying them
* 🛠️ You are working with **class components or legacy code**

***

### 🔹 Real-World Use Cases

* Authentication (`withAuth`)
* Logging (`withLogger`)
* Permissions (`withRole`)
* Data fetching (`withData`)
* Redux (`connect` is a HOC)

***

## 2. ⚙️ Concepts / Internal Workings

***

### 🔹 1. HOC is Just a Function

```js theme={null}
function withExtraInfo(WrappedComponent) {
  return function Enhanced(props) {
    return <WrappedComponent {...props} extra="info" />;
  };
}
```

👉 No special React API — just JavaScript function composition.

***

### 🔹 2. Component Wrapping

HOC creates a **wrapper component**:

```js theme={null}
const Enhanced = withFeature(Component);
```

Internally:

```js theme={null}
function Enhanced(props) {
  return <Component {...props} extraProp="value" />;
}
```

***

### 🔹 3. Props Forwarding

Critical concept:

* HOC must pass original props

```js theme={null}
return <WrappedComponent {...props} />;
```

👉 Otherwise → props get lost ❌

***

### 🔹 4. Composition Over Inheritance

HOCs follow React’s philosophy:

> Prefer composition over inheritance

* HOC composes behavior
* Does NOT extend component class

***

### 🔹 5. Pure vs Impure HOCs

✔ Pure HOC:

* Does not modify original component

❌ Impure HOC:

```js theme={null}
WrappedComponent.prototype.componentDidMount = ...
```

👉 Never mutate the original component

***

### 🔹 6. Relationship with Other Patterns

| Pattern      | Relationship                     |
| ------------ | -------------------------------- |
| Render Props | Alternative for logic reuse      |
| Hooks        | Modern replacement for most HOCs |
| Context      | Often used inside HOCs           |
| Composition  | HOCs are composition-based       |

***

### 🔹 7. How React Handles HOCs Internally

React treats:

```js theme={null}
<EnhancedComponent />
```

As:

* A normal component
* Wrapper renders inner component

👉 No special optimization — just nested components

***

## 3. 🧪 Syntax & Examples

***

### 🔹 Basic HOC Example

```js theme={null}
function withLogger(WrappedComponent) {
  return function Enhanced(props) {
    console.log("Props:", props);
    return <WrappedComponent {...props} />;
  };
}
```

#### Usage:

```js theme={null}
const LoggedComponent = withLogger(MyComponent);
```

***

### 🔹 Example: Authentication HOC

```js theme={null}
function withAuth(WrappedComponent) {
  return function Enhanced(props) {
    const isLoggedIn = true;

    if (!isLoggedIn) {
      return <p>Please login</p>;
    }

    return <WrappedComponent {...props} />;
  };
}
```

***

### 🔹 Example: Data Fetching HOC

```js theme={null}
function withData(url) {
  return function (WrappedComponent) {
    return function Enhanced(props) {
      const [data, setData] = useState(null);

      useEffect(() => {
        fetch(url).then(res => res.json()).then(setData);
      }, [url]);

      return <WrappedComponent {...props} data={data} />;
    };
  };
}
```

#### Usage:

```js theme={null}
const UserComponent = withData("/api/user")(User);
```

***

### 🔹 Example: Conditional Rendering HOC

```js theme={null}
function withLoading(WrappedComponent) {
  return function ({ isLoading, ...props }) {
    if (isLoading) return <p>Loading...</p>;
    return <WrappedComponent {...props} />;
  };
}
```

***

### 🔹 Composing Multiple HOCs

```js theme={null}
const Enhanced = withAuth(withLogger(MyComponent));
```

***

### 🔹 Variation: Using Utility Composition

```js theme={null}
const compose = (...fns) => (comp) =>
  fns.reduceRight((acc, fn) => fn(acc), comp);

const Enhanced = compose(withAuth, withLogger)(MyComponent);
```

***

## 4. ⚠️ Edge Cases / Common Mistakes

***

### 🔹 1. Not Forwarding Props

```js theme={null}
return <WrappedComponent />; // ❌
```

👉 Props lost

✅ Fix:

```js theme={null}
return <WrappedComponent {...props} />;
```

***

### 🔹 2. Mutating Wrapped Component

```js theme={null}
WrappedComponent.someMethod = ... // ❌
```

👉 Breaks component integrity

***

### 🔹 3. Losing Static Methods

```js theme={null}
MyComponent.staticMethod = () => {};
```

HOC removes it ❌

### ✅ Fix:

```js theme={null}
import hoistNonReactStatics from "hoist-non-react-statics";

hoistNonReactStatics(Enhanced, WrappedComponent);
```

***

### 🔹 4. Ref Not Forwarded

```js theme={null}
<Enhanced ref={ref} /> // ❌ doesn't work
```

### ✅ Fix:

```js theme={null}
const Enhanced = React.forwardRef((props, ref) => (
  <WrappedComponent {...props} ref={ref} />
));
```

***

### 🔹 5. Wrapper Hell

```js theme={null}
withA(withB(withC(Component)))
```

👉 Hard to debug

***

### 🔹 6. Props Collision

```js theme={null}
return <WrappedComponent {...props} user="admin" />;
```

👉 Overwrites existing `user`

***

### 🔹 7. Debugging Difficulty

* DevTools show wrapper names instead of actual component

***

### 🔹 8. Performance Issues

* Extra component layer
* Unnecessary re-renders

***

## 5. ✅ Best Practices

***

### 🔹 1. Always Forward Props

```js theme={null}
<WrappedComponent {...props} />
```

***

### 🔹 2. Use Clear Naming

```js theme={null}
withAuth
withLogger
withData
```

***

### 🔹 3. Set Display Name

```js theme={null}
Enhanced.displayName = `withAuth(${WrappedComponent.displayName})`;
```

👉 Improves debugging

***

### 🔹 4. Avoid Side Effects in HOC Body

✔ Use lifecycle hooks (`useEffect`)

***

### 🔹 5. Prefer Pure HOCs

* Don’t mutate wrapped component
* Return new component

***

### 🔹 6. Optimize with Memoization

```js theme={null}
return React.memo(Enhanced);
```

***

### 🔹 7. Avoid Deep Nesting

✔ Use composition helpers

***

### 🔹 8. Use ForwardRef When Needed

```js theme={null}
React.forwardRef(...)
```

***

### 🔹 9. Prefer Hooks for New Code

👉 Modern React:

❌ HOC:

```js theme={null}
const Enhanced = withData(Component);
```

✔ Hook:

```js theme={null}
const data = useData();
```

***

### 🔹 10. Keep HOCs Focused

❌ Bad:

```js theme={null}
withEverything()
```

✔ Good:

```js theme={null}
withAuth()
withLogger()
```

***

# 🧠 Final Mental Model

* HOC = **Component → Enhanced Component**
* Used for:

  * Logic reuse
  * Cross-cutting concerns
* Downsides:

  * Wrapper nesting
  * Performance overhead
  * Debugging complexity

***

## 🔚 Key Insight

HOCs are part of React’s evolution:

* **Before:** Mixins ❌
* **Then:** HOCs ✅
* **Then:** Render Props ✅
* **Now:** Hooks 🚀

👉 Understanding HOCs helps you:

* Maintain legacy code
* Understand composition deeply
* Appreciate why hooks exist

***

# 🧠 Senior-Level Conceptual Questions — Higher-Order Components (HOCs)

***

## 1. Why were HOCs introduced, and what core problem do they solve?

### ✅ Answer

HOCs were introduced to solve **cross-cutting concerns and logic reuse** before hooks existed.

### 🔴 Problem:

* Logic duplication across components
* No clean way to share stateful behavior

### 🟢 Solution:

Wrap components to inject behavior:

```js theme={null}
const Enhanced = withAuth(Component);
```

### 💡 Why this works:

* Promotes **composition over inheritance**
* Keeps components focused on UI

### 🔁 Comparison:

* HOCs vs Render Props → less nesting
* HOCs vs Hooks → more structural overhead

***

## 2. How does React treat a HOC internally?

### ✅ Answer

React treats a HOC as:

* Just another component layer

```js theme={null}
const Enhanced = withFeature(Component);
```

Internally:

```js theme={null}
function Enhanced(props) {
  return <Component {...props} extra="value" />;
}
```

### 💡 Key Insight:

* No special React optimization
* Just nested component rendering

### ⚠️ Implication:

* Adds extra layer → affects performance & debugging

***

## 3. What are the risks of mutating the wrapped component inside a HOC?

### ✅ Answer

```js theme={null}
WrappedComponent.someMethod = () => {}; // ❌
```

### 🔴 Problems:

* Breaks encapsulation
* Causes side effects across usages
* Hard-to-debug shared state

### 💡 Why:

Components should be treated as **pure inputs**

### ✅ Correct Approach:

Always return a **new component**

***

## 4. Why is prop forwarding critical in HOCs?

### ✅ Answer

```js theme={null}
return <WrappedComponent {...props} />;
```

### 💡 Why:

* HOC sits between parent and wrapped component
* Without forwarding → props are lost

### 🔴 Failure case:

```js theme={null}
return <WrappedComponent />; // ❌
```

👉 Breaks component contract

***

## 5. What is “wrapper hell” in HOCs, and how does it affect architecture?

### ✅ Answer

```js theme={null}
withA(withB(withC(Component)))
```

### 🔴 Problems:

* Deep nesting
* Hard debugging
* Poor readability

### 💡 Why:

Each HOC adds another abstraction layer

### 🟢 Solutions:

* Use composition helpers
* Replace with hooks

***

## 6. How do HOCs impact performance?

### ✅ Answer

### 🔴 Costs:

* Extra component layers
* Additional renders
* Prop propagation overhead

### 💡 Why:

React must reconcile:

* Wrapper component
* Wrapped component

### 🟢 Optimization:

```js theme={null}
return React.memo(Enhanced);
```

***

## 7. Why do HOCs often cause prop name collisions?

### ✅ Answer

```js theme={null}
return <WrappedComponent {...props} user="admin" />;
```

### 🔴 Problem:

* Overwrites existing props

### 💡 Why:

Props are merged blindly

### 🟢 Fix:

* Namespace props
* Use clear naming

***

## 8. How do HOCs affect static methods on components?

### ✅ Answer

```js theme={null}
Component.fetchData = () => {};
```

After wrapping:

```js theme={null}
const Enhanced = withHOC(Component);
```

👉 Static method is lost ❌

### 💡 Why:

New component doesn’t inherit statics

### 🟢 Fix:

```js theme={null}
hoistNonReactStatics(Enhanced, Component);
```

***

## 9. Why don’t refs work directly with HOCs?

### ✅ Answer

```js theme={null}
<Enhanced ref={ref} /> // ❌
```

### 💡 Why:

Ref attaches to wrapper, not inner component

### 🟢 Fix:

```js theme={null}
const Enhanced = React.forwardRef((props, ref) => (
  <WrappedComponent {...props} ref={ref} />
));
```

***

## 10. What are the trade-offs between HOCs and render props?

### ✅ Answer

| Aspect      | HOC                | Render Props          |
| ----------- | ------------------ | --------------------- |
| Structure   | Wrapper            | Inline function       |
| Flexibility | Limited            | High                  |
| Readability | Better (initially) | Degrades with nesting |
| Debugging   | Hard               | Easier                |

### 💡 Insight:

* HOCs are better for structural composition
* Render props better for dynamic UI control

***

## 11. What are the trade-offs between HOCs and hooks?

### ✅ Answer

| Aspect      | HOC          | Hooks      |
| ----------- | ------------ | ---------- |
| Readability | Lower        | Higher     |
| Nesting     | Wrapper hell | Flat       |
| Performance | Extra layers | Better     |
| Flexibility | Structural   | Functional |

### 💡 Conclusion:

Hooks are preferred for most modern use cases

***

## 12. When would you still use HOCs in modern React?

### ✅ Answer

Use HOCs when:

* Working with **class components**
* Integrating with **legacy libraries (e.g., Redux connect)**
* Need **cross-cutting concerns applied declaratively**

### 💡 Example:

```js theme={null}
export default withAuth(withLogger(Component));
```

***

## 13. How would you design a reusable HOC API?

### ✅ Answer

Principles:

* Minimal API
* Clear naming
* No side effects

```js theme={null}
function withFeature(WrappedComponent) {
  return function Enhanced(props) {
    return <WrappedComponent {...props} feature />;
  };
}
```

### 💡 Why:

* Keeps abstraction predictable

***

## 14. What are common debugging challenges with HOCs?

### ✅ Answer

* Wrapper names in DevTools
* Hard to trace props flow
* Multiple layers obscure logic

### 🟢 Fix:

```js theme={null}
Enhanced.displayName = `withFeature(${Wrapped.displayName})`;
```

***

## 15. How do HOCs interact with React’s reconciliation?

### ✅ Answer

Each HOC adds:

* New component boundary
* Separate reconciliation step

### 💡 Why:

React compares:

* Wrapper component
* Then wrapped component

👉 More layers → more work

***

## 16. Can HOCs cause unnecessary re-renders? How?

### ✅ Answer

Yes:

```js theme={null}
function withData(Wrapped) {
  return function(props) {
    const data = {}; // new object each render
    return <Wrapped {...props} data={data} />;
  };
}
```

### 💡 Why:

New object reference → child re-renders

### 🟢 Fix:

Use memoization

***

## 17. What is a “parameterized HOC” and why is it useful?

### ✅ Answer

```js theme={null}
function withData(url) {
  return function(Wrapped) {
    return function(props) {
      // fetch using url
    };
  };
}
```

### 💡 Why:

* Makes HOC configurable
* Reusable across scenarios

***

## 18. How do you compose multiple HOCs safely?

### ✅ Answer

```js theme={null}
const compose = (...fns) => (comp) =>
  fns.reduceRight((acc, fn) => fn(acc), comp);
```

### 💡 Why:

* Avoids deep nesting
* Improves readability

***

## 🔚 Final Insight

At senior level, HOCs are about:

* Understanding **composition deeply**
* Knowing **why they were replaced by hooks**
* Making **correct architectural decisions**

👉 Strong engineers:

* Don’t just use HOCs
* They **evaluate trade-offs and evolve patterns** based on context

***

# 🧠 Senior-Level MCQs — Higher-Order Components (Deep Understanding)

***

## 1. What is the most subtle risk when a HOC does NOT forward props correctly?

### Options:

A. Component fails to render
B. Props silently disappear, breaking downstream logic
C. React throws an error
D. Only optional props are lost

### ✅ Correct Answer: **B**

### 💡 Explanation:

If props are not forwarded:

```js theme={null}
return <WrappedComponent />; // ❌
```

All incoming props are lost → downstream components break silently.

### ❌ Why others are wrong:

* A: Component may still render
* C: React does not throw an error
* D: All props (not just optional) are lost

***

## 2. What happens to static methods on a component wrapped by a HOC?

### Options:

A. Automatically copied
B. Lost unless explicitly hoisted
C. Only class methods are preserved
D. React warns about it

### ✅ Correct Answer: **B**

### 💡 Explanation:

HOCs return a new component → original static methods are not inherited.

### ❌ Why others are wrong:

* A: Not automatic
* C: Not true
* D: No warning

***

## 3. Why can HOCs lead to “wrapper hell”?

### Options:

A. Too many DOM nodes
B. Deeply nested component wrappers
C. Infinite loops
D. Hook violations

### ✅ Correct Answer: **B**

### 💡 Explanation:

```js theme={null}
withA(withB(withC(Component)))
```

Creates deeply nested wrappers → hard to debug and maintain.

### ❌ Why others are wrong:

* A: DOM nodes not necessarily affected
* C/D: Not inherent

***

## 4. What is the main reason refs don’t work directly with HOCs?

### Options:

A. Refs are deprecated
B. Refs attach to wrapper instead of inner component
C. HOCs block refs
D. Only class components support refs

### ✅ Correct Answer: **B**

### 💡 Explanation:

Ref points to outer component, not wrapped one.

### ❌ Why others are wrong:

* A: Incorrect
* C: Not blocked
* D: Functional components support refs via `forwardRef`

***

## 5. What is the risk of mutating the wrapped component inside a HOC?

### Options:

A. Improves performance
B. Causes shared side effects across usages
C. Prevents re-renders
D. Only affects dev mode

### ✅ Correct Answer: **B**

### 💡 Explanation:

Mutating the component affects all usages → unpredictable bugs.

### ❌ Why others are wrong:

* A: Opposite effect
* C: Not related
* D: Happens everywhere

***

## 6. What is the primary performance cost of using HOCs?

### Options:

A. Extra DOM elements
B. Additional component layers
C. Slower JavaScript execution
D. Memory leaks

### ✅ Correct Answer: **B**

### 💡 Explanation:

Each HOC adds a wrapper → extra reconciliation step.

### ❌ Why others are wrong:

* A: Not always
* C: Minimal impact
* D: Not inherent

***

## 7. Why can HOCs cause prop name collisions?

### Options:

A. Props are merged shallowly
B. React merges props incorrectly
C. Props are immutable
D. HOCs remove existing props

### ✅ Correct Answer: **A**

### 💡 Explanation:

```js theme={null}
<WrappedComponent {...props} user="admin" />
```

Overrides `user` prop.

### ❌ Why others are wrong:

* B: React behaves correctly
* C: Not relevant
* D: Not removed, overwritten

***

## 8. What is the correct way to preserve static methods in HOCs?

### Options:

A. React.memo
B. useCallback
C. hoistNonReactStatics
D. forwardRef

### ✅ Correct Answer: **C**

### 💡 Explanation:

Utility copies static properties from wrapped component.

### ❌ Why others are wrong:

* A/B/D: Unrelated

***

## 9. What is a key difference between HOCs and hooks?

### Options:

A. Hooks cannot share logic
B. HOCs modify component structure
C. Hooks are slower
D. HOCs cannot manage state

### ✅ Correct Answer: **B**

### 💡 Explanation:

HOCs wrap components → change structure
Hooks → reuse logic without wrappers

### ❌ Why others are wrong:

* A: Hooks share logic well
* C: Incorrect
* D: HOCs can manage state

***

## 10. What happens if a HOC creates a new object prop on every render?

```js theme={null}
const data = {};
```

### Options:

A. No effect
B. Causes unnecessary re-renders
C. Causes infinite loop
D. React throws warning

### ✅ Correct Answer: **B**

### 💡 Explanation:

New reference → child sees prop change → re-render

### ❌ Why others are wrong:

* A: Incorrect
* C: No loop
* D: No warning

***

## 11. Why is `displayName` important in HOCs?

### Options:

A. Improves performance
B. Helps debugging in DevTools
C. Required by React
D. Prevents re-renders

### ✅ Correct Answer: **B**

### 💡 Explanation:

Without it, DevTools show generic names.

### ❌ Why others are wrong:

* A: No performance impact
* C: Not required
* D: Not related

***

## 12. What is a parameterized HOC?

### Options:

A. HOC with state
B. HOC returning another function
C. HOC using hooks
D. HOC without props

### ✅ Correct Answer: **B**

### 💡 Explanation:

```js theme={null}
const withData = (url) => (Component) => { ... }
```

### ❌ Why others are wrong:

* A: Not defining feature
* C: Not required
* D: Incorrect

***

## 13. What happens if a HOC updates state during render?

### Options:

A. Works fine
B. Infinite re-render loop
C. Only one extra render
D. React prevents it

### ✅ Correct Answer: **B**

### 💡 Explanation:

State update → re-render → loop

### ❌ Why others are wrong:

* A: Incorrect
* C: Not limited
* D: React doesn’t block

***

## 14. What is the main drawback of deeply composed HOCs?

### Options:

A. Increased bundle size
B. Hard-to-debug component tree
C. Slower network calls
D. Hook violations

### ✅ Correct Answer: **B**

### 💡 Explanation:

Nested wrappers obscure logic and data flow.

### ❌ Why others are wrong:

* A: Minor impact
* C: Unrelated
* D: Not inherent

***

## 15. How do HOCs affect React DevTools visibility?

### Options:

A. Show original component only
B. Show wrapper components
C. Hide component tree
D. Break DevTools

### ✅ Correct Answer: **B**

### 💡 Explanation:

Each HOC appears as a separate component layer.

### ❌ Why others are wrong:

* A: Incorrect
* C/D: Not true

***

## 16. Why should HOCs be pure functions?

### Options:

A. To improve performance
B. To avoid mutating wrapped components
C. To reduce bundle size
D. Required by React

### ✅ Correct Answer: **B**

### 💡 Explanation:

Purity ensures predictable behavior and avoids side effects.

### ❌ Why others are wrong:

* A: Secondary
* C: Not relevant
* D: Not required

***

## 17. What is the main architectural downside of HOCs compared to hooks?

### Options:

A. Cannot reuse logic
B. Introduce structural complexity
C. Cannot handle async logic
D. Break component lifecycle

### ✅ Correct Answer: **B**

### 💡 Explanation:

HOCs add wrapper layers → complexity

### ❌ Why others are wrong:

* A: They reuse logic
* C: Can handle async
* D: Not true

***

## 18. When is using HOCs still justified in modern React?

### Options:

A. Always
B. Never
C. Legacy code or library APIs
D. Only for performance

### ✅ Correct Answer: **C**

### 💡 Explanation:

Used in:

* Legacy apps
* Libraries (e.g., Redux `connect`)

### ❌ Why others are wrong:

* A/B: Extremes
* D: Not primary reason

***

## 19. What is the effect of wrapping a component with multiple HOCs on render performance?

### Options:

A. No impact
B. Linear increase in rendering layers
C. Exponential slowdown
D. Only affects dev mode

### ✅ Correct Answer: **B**

### 💡 Explanation:

Each HOC adds one layer → linear overhead.

### ❌ Why others are wrong:

* A: Incorrect
* C: Not exponential
* D: Happens in production too

***

# 🔚 Final Insight

These MCQs test:

* Deep understanding of composition
* React internals (reconciliation, props, refs)
* Real-world trade-offs

👉 Senior-level takeaway:
HOCs are not just a pattern —
They represent **how React evolved toward hooks** and why structural abstraction matters.

***

# 🧠 Higher-Order Components — Real-World Coding Problems (Senior Level)

***

## 1. 🟡 Build `withAuth` (Route Protection)

### 📌 Problem

Create a HOC that restricts access to authenticated users.

### Constraints

* Redirect or show fallback if not authenticated
* Should not modify wrapped component

### Expected Behavior

```js id="qhz8qa" theme={null}
const Protected = withAuth(Dashboard);
```

### Edge Cases

* Auth state changes dynamically
* Async auth check

### 🪜 Solution Approach

1. Read auth state (context/localStorage)
2. Conditionally render fallback or component
3. Forward props properly

```js id="9u8q4m" theme={null}
function withAuth(Wrapped) {
  return function(props) {
    const isAuth = true;
    if (!isAuth) return <p>Login required</p>;
    return <Wrapped {...props} />;
  };
}
```

***

## 2. 🟡 Build `withLogger`

### 📌 Problem

Log props and lifecycle events

### Constraints

* Should not affect component behavior

### Expected Behavior

Logs props on render

### Edge Cases

* Frequent re-renders

### 🪜 Approach

* Wrap component
* Log props before rendering

***

## 3. 🟡 Build `withLoading`

### 📌 Problem

Show loading UI based on prop

### Expected Behavior

```js id="6tfl4x" theme={null}
const Enhanced = withLoading(Component);
<Enhanced isLoading />
```

### Edge Cases

* Missing prop

### 🪜 Approach

* Destructure `isLoading`
* Render fallback or wrapped component

***

## 4. 🟠 Build `withErrorBoundary`

### 📌 Problem

Catch runtime errors in wrapped component

### Constraints

* Use class component (error boundaries)

### Edge Cases

* Nested HOCs

### 🪜 Approach

* Implement `componentDidCatch`
* Wrap component safely

***

## 5. 🟠 Build `withDataFetching`

### 📌 Problem

Fetch data and inject into component

### Constraints

* Handle loading + error

### Edge Cases

* URL changes
* Abort requests

### 🪜 Approach

* Use `useEffect`
* Store state
* Inject `data` prop

***

## 6. 🟠 Build `withPermissions`

### 📌 Problem

Restrict rendering based on roles

### Expected Behavior

```js id="hxlpua" theme={null}
const AdminOnly = withPermission("admin")(Component);
```

### Edge Cases

* Multiple roles

### 🪜 Approach

* Accept role parameter
* Compare with user roles

***

## 7. 🟠 Build `withDebounce`

### 📌 Problem

Debounce a prop value before passing it

### Edge Cases

* Rapid updates

### 🪜 Approach

* Use `setTimeout`
* Update value after delay

***

## 8. 🟠 Build `withLocalStorage`

### 📌 Problem

Persist component state to localStorage

### Edge Cases

* JSON parsing errors

### 🪜 Approach

* Initialize from storage
* Sync on update

***

## 9. 🔴 Build `withInfiniteScroll`

### 📌 Problem

Add infinite scrolling capability

### Constraints

* Trigger fetch near bottom

### Edge Cases

* Fast scrolling
* Duplicate calls

### 🪜 Approach

1. Track scroll
2. Detect threshold
3. Fetch more data

***

## 10. 🔴 Build `withUndoRedo`

### 📌 Problem

Add undo/redo capability to any component

### Edge Cases

* History overflow

### 🪜 Approach

* Maintain history array
* Track index pointer
* Inject handlers

***

## 11. 🔴 Build `withFeatureFlag`

### 📌 Problem

Enable/disable features dynamically

### Edge Cases

* Async flag fetch

### 🪜 Approach

* Fetch flags
* Inject boolean flag

***

## 12. 🔴 Build `withAnalytics`

### 📌 Problem

Track user interactions

### Constraints

* Should not affect UI

### Edge Cases

* High-frequency events

### 🪜 Approach

* Wrap event handlers
* Send analytics

***

## 13. 🔴 Build `withResizeObserver`

### 📌 Problem

Inject element dimensions

### Edge Cases

* Multiple instances

### 🪜 Approach

* Use `ResizeObserver`
* Pass size via props

***

## 14. 🔴 Build `withCache`

### 📌 Problem

Cache API responses across components

### Edge Cases

* Cache invalidation

### 🪜 Approach

* Use Map
* Check before fetch

***

## 15. 🔴 Build `withKeyboardShortcut`

### 📌 Problem

Handle keyboard shortcuts globally

### Edge Cases

* Conflicting shortcuts

### 🪜 Approach

* Listen to keydown
* Match keys
* Trigger callback

***

## 16. 🔴 Build `withPolling`

### 📌 Problem

Poll API at intervals

### Edge Cases

* Stop on unmount

### 🪜 Approach

* Use interval
* Cleanup properly

***

## 17. 🔴 Build `withDrag`

### 📌 Problem

Add drag functionality

### Edge Cases

* Drop outside

### 🪜 Approach

* Track mouse events
* Inject handlers

***

## 18. 🔴 Build `withFormState`

### 📌 Problem

Manage form state for any component

### Edge Cases

* Dynamic fields

### 🪜 Approach

* Use reducer
* Inject handlers

***

## 19. 🔴 Build `withMemoizedProps`

### 📌 Problem

Prevent unnecessary re-renders by memoizing props

### Edge Cases

* Deep objects

### 🪜 Approach

* Use `useMemo`
* Compare dependencies

***

# 🔚 Final Insight

These problems test:

* Component composition
* Abstraction design
* Performance awareness
* Real-world architecture

👉 Senior-level expectation:
You should:

* Design clean HOCs
* Avoid pitfalls (props, refs, statics)
* Know when to replace with hooks

***

# 🛠️ Senior Code Review — Higher-Order Components (HOCs) Debugging Challenges

***

## 1. ❗ Props Not Forwarded

```js id="hoc1" theme={null}
function withLogger(Wrapped) {
  return function Enhanced() {
    console.log("render");
    return <Wrapped />; // ❌
  };
}
```

### 🔍 What’s wrong?

Original props are not passed to the wrapped component.

### 💡 Why it happens

HOC sits between parent and child. Without forwarding, props are lost.

### ✅ Fix

```js id="hoc1fix" theme={null}
return function Enhanced(props) {
  console.log("render");
  return <Wrapped {...props} />;
};
```

### 🧠 Best Practice

Always forward all props unless intentionally filtering.

***

## 2. ❗ Static Methods Lost

```js id="hoc2" theme={null}
function withData(Wrapped) {
  return function Enhanced(props) {
    return <Wrapped {...props} />;
  };
}
```

### 🔍 What’s wrong?

Static methods on `Wrapped` are lost.

### 💡 Why

New component does not inherit static properties.

### ✅ Fix

```js id="hoc2fix" theme={null}
import hoistNonReactStatics from "hoist-non-react-statics";

function withData(Wrapped) {
  function Enhanced(props) {
    return <Wrapped {...props} />;
  }

  hoistNonReactStatics(Enhanced, Wrapped);
  return Enhanced;
}
```

### 🧠 Best Practice

Always hoist statics in reusable HOCs.

***

## 3. ❗ Ref Not Forwarded

```js id="hoc3" theme={null}
function withWrapper(Wrapped) {
  return function(props) {
    return <Wrapped {...props} />;
  };
}
```

### 🔍 What’s wrong?

Refs passed to Enhanced component won’t reach wrapped component.

### 💡 Why

Refs attach to outer component.

### ✅ Fix

```js id="hoc3fix" theme={null}
const withWrapper = (Wrapped) =>
  React.forwardRef((props, ref) => (
    <Wrapped {...props} ref={ref} />
  ));
```

### 🧠 Best Practice

Use `forwardRef` when HOC is used with refs.

***

## 4. ❗ Infinite Re-render Loop

```js id="hoc4" theme={null}
function withState(Wrapped) {
  return function(props) {
    const [count, setCount] = useState(0);
    setCount(count + 1); // ❌

    return <Wrapped {...props} count={count} />;
  };
}
```

### 🔍 What’s wrong?

State updated during render.

### 💡 Why

Triggers re-render → infinite loop.

### ✅ Fix

```js id="hoc4fix" theme={null}
useEffect(() => {
  setCount(c => c + 1);
}, []);
```

### 🧠 Best Practice

Never update state inside render phase.

***

## 5. ❗ Prop Collision

```js id="hoc5" theme={null}
function withUser(Wrapped) {
  return function(props) {
    return <Wrapped {...props} user="admin" />;
  };
}
```

### 🔍 What’s wrong?

Overwrites existing `user` prop.

### 💡 Why

Props spread order overrides previous values.

### ✅ Fix

```js id="hoc5fix" theme={null}
return <Wrapped {...props} injectedUser="admin" />;
```

### 🧠 Best Practice

Namespace injected props to avoid collisions.

***

## 6. ❗ Unstable Object Causing Re-renders

```js id="hoc6" theme={null}
function withConfig(Wrapped) {
  return function(props) {
    const config = { theme: "dark" }; // ❌ new each render
    return <Wrapped {...props} config={config} />;
  };
}
```

### 🔍 What’s wrong?

New object reference every render.

### 💡 Why

Breaks memoization → unnecessary re-renders.

### ✅ Fix

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

### 🧠 Best Practice

Memoize objects/functions passed as props.

***

## 7. ❗ Event Listener Leak

```js id="hoc7" theme={null}
function withScroll(Wrapped) {
  return function(props) {
    useEffect(() => {
      window.addEventListener("scroll", () => console.log("scroll"));
    }, []);

    return <Wrapped {...props} />;
  };
}
```

### 🔍 What’s wrong?

Listener never removed.

### 💡 Why

Missing cleanup → memory leak.

### ✅ Fix

```js id="hoc7fix" theme={null}
useEffect(() => {
  const handler = () => console.log("scroll");
  window.addEventListener("scroll", handler);
  return () => window.removeEventListener("scroll", handler);
}, []);
```

### 🧠 Best Practice

Always cleanup side effects.

***

## 8. ❗ Incorrect Dependency in Effect

```js id="hoc8" theme={null}
useEffect(() => {
  fetchData();
}, []); // ❌ ignoring props.url
```

### 🔍 What’s wrong?

Effect does not respond to prop changes.

### 💡 Why

Missing dependency → stale data.

### ✅ Fix

```js id="hoc8fix" theme={null}
useEffect(() => {
  fetchData();
}, [props.url]);
```

### 🧠 Best Practice

Always include external dependencies.

***

## 9. ❗ Mutating Props

```js id="hoc9" theme={null}
function withMutation(Wrapped) {
  return function(props) {
    props.value = "changed"; // ❌
    return <Wrapped {...props} />;
  };
}
```

### 🔍 What’s wrong?

Mutates incoming props.

### 💡 Why

Violates React immutability → unpredictable bugs.

### ✅ Fix

```js id="hoc9fix" theme={null}
return <Wrapped {...props} value="changed" />;
```

### 🧠 Best Practice

Never mutate props.

***

## 10. ❗ Missing Display Name

```js id="hoc10" theme={null}
function withFeature(Wrapped) {
  return function(props) {
    return <Wrapped {...props} />;
  };
}
```

### 🔍 What’s wrong?

Hard to debug in DevTools.

### 💡 Why

Component appears as anonymous.

### ✅ Fix

```js id="hoc10fix" theme={null}
Enhanced.displayName = `withFeature(${Wrapped.displayName || Wrapped.name})`;
```

### 🧠 Best Practice

Always set `displayName`.

***

## 11. ❗ Over-fetching Data

```js id="hoc11" theme={null}
useEffect(() => {
  fetch("/api").then(setData);
}); // ❌ no dependency
```

### 🔍 What’s wrong?

Runs on every render.

### 💡 Why

Missing dependency array.

### ✅ Fix

```js id="hoc11fix" theme={null}
useEffect(() => {
  fetch("/api").then(setData);
}, []);
```

***

## 12. ❗ Wrapper Hell Performance Issue

```js id="hoc12" theme={null}
export default withA(withB(withC(Component)));
```

### 🔍 What’s wrong?

Deep nesting → performance + readability issues.

### 💡 Why

Each layer adds render overhead.

### ✅ Fix

```js id="hoc12fix" theme={null}
const Enhanced = compose(withA, withB, withC)(Component);
```

### 🧠 Best Practice

Flatten composition or use hooks.

***

## 13. ❗ Async Race Condition

```js id="hoc13" theme={null}
useEffect(() => {
  fetch(`/api/${id}`).then(setData);
}, [id]);
```

### 🔍 What’s wrong?

Older requests may override newer ones.

### 💡 Why

Async calls resolve out of order.

### ✅ Fix

```js id="hoc13fix" theme={null}
useEffect(() => {
  let active = true;

  fetch(`/api/${id}`).then(data => {
    if (active) setData(data);
  });

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

***

## 14. ❗ Breaking Memoization

```js id="hoc14" theme={null}
return <Wrapped {...props} onClick={() => doSomething()} />;
```

### 🔍 What’s wrong?

New function each render.

### 💡 Why

Breaks `React.memo`.

### ✅ Fix

```js id="hoc14fix" theme={null}
const handleClick = useCallback(() => doSomething(), []);
```

***

## 15. ❗ Conditional Hook Usage Inside HOC

```js id="hoc15" theme={null}
if (props.enabled) {
  useEffect(() => {});
}
```

### 🔍 What’s wrong?

Violates Rules of Hooks.

### 💡 Why

Hooks must run in same order.

### ✅ Fix

```js id="hoc15fix" theme={null}
useEffect(() => {
  if (props.enabled) { }
}, [props.enabled]);
```

***

## 16. ❗ Recreating HOC Inside Render

```js id="hoc16" theme={null}
function Parent() {
  const Enhanced = withFeature(Component); // ❌
  return <Enhanced />;
}
```

### 🔍 What’s wrong?

New component created every render.

### 💡 Why

Breaks React identity → remounts component.

### ✅ Fix

```js id="hoc16fix" theme={null}
const Enhanced = withFeature(Component);
function Parent() {
  return <Enhanced />;
}
```

### 🧠 Best Practice

Create HOCs outside render.

***

## 🔚 Final Takeaway

These issues highlight:

* **Structural pitfalls** (wrapper hell, refs)
* **Performance traps** (new objects/functions)
* **React rules violations** (hooks, state updates)
* **Subtle bugs** (race conditions, prop mutation)

***

👉 Senior-level expectation:
You should be able to:

* Predict behavior across wrapper layers
* Control rendering and props precisely
* Decide when to replace HOCs with hooks

***

# 🧠 Senior Frontend Architect — Higher-Order Components (HOC) Machine Coding Problems

***

## 1. 🔴 Authentication Guard System (`withAuth`)

### 📌 Requirements

* Restrict access to authenticated users
* Redirect or show fallback UI if unauthenticated
* Support async auth validation

### 🖥️ UI Behavior

* Logged-in → render protected component
* Logged-out → show login screen / redirect

### 🔄 State/Data Flow

* Auth state (context/localStorage/API) → HOC → wrapped component

### ⚠️ Edge Cases

* Token expiry mid-session
* Async auth delay (loading state)
* Multiple protected routes

### ⚡ Performance

* Avoid re-checking auth unnecessarily
* Cache auth state

### 🏗️ Architecture

* `withAuth(Component)`
* Use context for global auth state

### 🪜 Approach

1. Read auth state from context
2. Handle loading state
3. Conditionally render wrapped component or fallback
4. Forward props correctly

***

## 2. 🔴 Role-Based Access Control (`withPermission`)

### 📌 Requirements

* Restrict component rendering based on user roles
* Support multiple roles

### 🖥️ UI Behavior

* Authorized → render component
* Unauthorized → show fallback

### 🔄 Data Flow

* User roles → HOC → validation → render

### ⚠️ Edge Cases

* Multiple roles
* Role updates dynamically

### ⚡ Performance

* Memoize role checks

### 🏗️ Architecture

```js theme={null}
withPermission(["admin", "editor"])(Component)
```

### 🪜 Approach

1. Accept roles as parameter
2. Compare with user roles
3. Render conditionally

***

## 3. 🔴 Global Error Boundary Wrapper (`withErrorBoundary`)

### 📌 Requirements

* Catch runtime errors in wrapped component
* Show fallback UI

### 🖥️ UI Behavior

* Error → fallback screen
* Normal → render component

### ⚠️ Edge Cases

* Nested error boundaries
* Reset on retry

### ⚡ Performance

* Avoid unnecessary re-renders

### 🏗️ Architecture

* Class-based HOC (error boundaries require class)

### 🪜 Approach

1. Implement `componentDidCatch`
2. Track error state
3. Render fallback or wrapped component

***

## 4. 🔴 Data Fetching Layer (`withData`)

### 📌 Requirements

* Fetch API data and inject into component
* Handle loading, error, retry

### 🖥️ UI Behavior

* Loading spinner
* Error message
* Data view

### 🔄 Data Flow

* URL → fetch → state → props injection

### ⚠️ Edge Cases

* Race conditions
* URL changes
* Abort requests

### ⚡ Performance

* Cache responses
* Avoid duplicate requests

### 🏗️ Architecture

```js theme={null}
withData("/api/users")(Component)
```

### 🪜 Approach

1. Accept URL
2. Fetch data in `useEffect`
3. Handle loading/error
4. Inject data via props

***

## 5. 🔴 Analytics Tracking Wrapper (`withAnalytics`)

### 📌 Requirements

* Track user interactions (clicks, views)
* Should not affect UI behavior

### 🖥️ UI Behavior

* Transparent to user

### 🔄 Data Flow

* Events → analytics service

### ⚠️ Edge Cases

* High-frequency events
* Duplicate tracking

### ⚡ Performance

* Debounce/throttle events

### 🏗️ Architecture

* Wrap event handlers

### 🪜 Approach

1. Intercept props like `onClick`
2. Wrap handler
3. Send analytics event

***

## 6. 🔴 Feature Flag System (`withFeatureFlag`)

### 📌 Requirements

* Enable/disable features dynamically
* Flags fetched from API

### 🖥️ UI Behavior

* Feature enabled → show component
* Disabled → hide or fallback

### ⚠️ Edge Cases

* Async flag loading
* Fallback behavior

### ⚡ Performance

* Cache flags

### 🏗️ Architecture

```js theme={null}
withFeatureFlag("newDashboard")(Component)
```

***

## 7. 🔴 Infinite Scroll Enhancer (`withInfiniteScroll`)

### 📌 Requirements

* Add infinite scrolling capability

### 🖥️ UI Behavior

* Scroll → load more data

### 🔄 Data Flow

* Scroll event → fetch → append data

### ⚠️ Edge Cases

* Fast scrolling
* Duplicate fetches

### ⚡ Performance

* Throttle scroll
* Virtualization

### 🪜 Approach

1. Listen to scroll
2. Detect threshold
3. Fetch next page

***

## 8. 🔴 Undo/Redo State Manager (`withUndoRedo`)

### 📌 Requirements

* Add undo/redo functionality to any component

### 🔄 Data Flow

* State → history stack → index pointer

### ⚠️ Edge Cases

* Large history
* Reset behavior

### ⚡ Performance

* Limit history size

***

## 9. 🔴 Responsive Design Wrapper (`withMediaQuery`)

### 📌 Requirements

* Inject screen size info

### 🖥️ UI Behavior

* Mobile vs desktop rendering

### ⚠️ Edge Cases

* SSR compatibility

### ⚡ Performance

* Debounce resize

***

## 10. 🔴 LocalStorage Sync Wrapper (`withLocalStorage`)

### 📌 Requirements

* Persist component state

### ⚠️ Edge Cases

* Invalid JSON
* Key changes

### ⚡ Performance

* Avoid excessive writes

***

## 11. 🔴 Polling System (`withPolling`)

### 📌 Requirements

* Fetch data periodically

### ⚠️ Edge Cases

* Stop polling on unmount
* Network errors

### ⚡ Performance

* Avoid overlapping requests

***

## 12. 🔴 Keyboard Shortcut Manager (`withShortcut`)

### 📌 Requirements

* Handle global keyboard shortcuts

### ⚠️ Edge Cases

* Conflicts between shortcuts

***

## 13. 🔴 Drag-and-Drop Enhancer (`withDrag`)

### 📌 Requirements

* Add drag functionality

### ⚠️ Edge Cases

* Drop outside target

***

## 14. 🔴 Form State Manager (`withFormState`)

### 📌 Requirements

* Manage form state and validation

### ⚠️ Edge Cases

* Dynamic fields
* Validation rules

***

## 15. 🔴 Cache Layer (`withCache`)

### 📌 Requirements

* Cache API responses

### ⚠️ Edge Cases

* Cache invalidation
* Stale data

***

## 16. 🔴 Resize Observer Wrapper (`withResizeObserver`)

### 📌 Requirements

* Inject element size

### ⚠️ Edge Cases

* Multiple elements

***

## 17. 🔴 Clipboard Manager (`withClipboard`)

### 📌 Requirements

* Copy text to clipboard
* Provide success state

***

## 18. 🔴 Route Guard System (`withRouteGuard`)

### 📌 Requirements

* Protect routes based on conditions

***

## 19. 🔴 Global Notification System (`withNotifications`)

### 📌 Requirements

* Trigger notifications globally

***

# 🔚 Final Insight

These problems simulate:

* Real-world production features
* Cross-cutting concerns (auth, analytics, caching)
* Architectural decisions

***

👉 Senior-level expectations:

* Design **clean, composable HOCs**
* Handle **edge cases and performance**
* Understand when to:

  * Use HOCs
  * Replace with hooks
  * Combine patterns

***

# 🧠 FAANG-Level Frontend Interview — Higher-Order Components (HOCs)

***

## 1. When would you choose an HOC over hooks in a modern React application?

### 🔍 Follow-up:

* Can hooks fully replace HOCs?
* What about library design?

### ✅ Strong Answer:

* Prefer HOCs when:

  * Working with **class components / legacy code**
  * Applying **cross-cutting concerns declaratively** (e.g., auth, analytics)
  * Building APIs like `connect` (Redux-style)
* Hooks are better for:

  * Local logic reuse
  * Cleaner composition

👉 HOCs still useful for **structural composition**

### ❌ Weak Answer:

> “Hooks always replace HOCs”

👉 Fails because:

* Ignores real-world legacy and library constraints

***

## 2. Explain how HOCs affect React’s rendering and reconciliation process.

### 🔍 Follow-up:

* What is the cost of multiple HOCs?

### ✅ Strong Answer:

* Each HOC introduces an extra component layer
* React must reconcile:

  * Wrapper component
  * Wrapped component

👉 More layers = more work (linear overhead)

### ❌ Weak Answer:

> “No difference”

👉 Fails because:

* Ignores component tree depth impact

***

## 3. What are the most common performance pitfalls with HOCs?

### 🔍 Follow-up:

* How would you detect them?

### ✅ Strong Answer:

* Creating new objects/functions each render
* Deep HOC nesting
* Unnecessary prop changes

```js theme={null}
return <Wrapped data={{}} /> // ❌ new object
```

### Fix:

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

### ❌ Weak Answer:

> “HOCs are slow”

👉 Fails because:

* No specifics or solutions

***

## 4. Why is prop forwarding critical in HOCs?

### 🔍 Follow-up:

* What happens if you forget it?

### ✅ Strong Answer:

* HOC sits between parent and child
* Without forwarding → props lost → bugs

```js theme={null}
return <Wrapped {...props} />;
```

### ❌ Weak Answer:

> “It passes props”

👉 Fails because:

* Doesn’t explain consequence of missing it

***

## 5. What is “wrapper hell” and how would you avoid it?

### 🔍 Follow-up:

* What alternatives exist?

### ✅ Strong Answer:

* Deep nesting of HOCs:

```js theme={null}
withA(withB(withC(Component)))
```

Problems:

* Hard debugging
* Poor readability

Solutions:

* Compose utility
* Replace with hooks

### ❌ Weak Answer:

> “Too many HOCs”

👉 Fails because:

* Doesn’t explain impact

***

## 6. How do HOCs handle refs, and what problems arise?

### 🔍 Follow-up:

* How do you fix it?

### ✅ Strong Answer:

* Ref attaches to wrapper, not inner component
* Use `forwardRef`

```js theme={null}
React.forwardRef((props, ref) => (
  <Wrapped {...props} ref={ref} />
));
```

### ❌ Weak Answer:

> “Refs don’t work”

👉 Fails because:

* Doesn’t explain why or solution

***

## 7. What happens to static methods when using HOCs?

### 🔍 Follow-up:

* How do you preserve them?

### ✅ Strong Answer:

* Static methods are lost
* Use `hoist-non-react-statics`

### ❌ Weak Answer:

> “They remain”

👉 Fails because:

* Incorrect

***

## 8. Design a robust `withData` HOC for production.

### 🔍 Follow-up:

* How do you handle caching and race conditions?

### ✅ Strong Answer:

Must include:

* Loading/error state
* AbortController / cleanup
* Dependency handling
* Optional caching layer

### ❌ Weak Answer:

> “Fetch and pass data”

👉 Fails because:

* Ignores production concerns

***

## 9. What are prop collision issues in HOCs?

### 🔍 Follow-up:

* How would you avoid them?

### ✅ Strong Answer:

* Injected props may override existing props

```js theme={null}
<Wrapped {...props} user="admin" />
```

Solutions:

* Namespace props
* Document API clearly

### ❌ Weak Answer:

> “Props merge”

👉 Fails because:

* Doesn’t highlight risk

***

## 10. How do you debug a deeply nested HOC issue in production?

### 🔍 Follow-up:

* What tools help?

### ✅ Strong Answer:

* Use React DevTools
* Inspect component tree layers
* Add `displayName`
* Log props at each layer

### ❌ Weak Answer:

> “Use console.log”

👉 Fails because:

* Too shallow

***

## 11. What are the trade-offs between HOCs and render props?

### 🔍 Follow-up:

* Which is more flexible?

### ✅ Strong Answer:

| HOC             | Render Props     |
| --------------- | ---------------- |
| Structural      | Dynamic UI       |
| Wrapper nesting | Callback nesting |
| Less flexible   | More flexible    |

👉 Render props give more runtime control

### ❌ Weak Answer:

> “Render props are newer”

👉 Fails because:

* No technical reasoning

***

## 12. What are the trade-offs between HOCs and hooks?

### 🔍 Follow-up:

* Why did hooks replace HOCs?

### ✅ Strong Answer:

* Hooks:

  * No wrapper layers
  * Better readability
  * Easier composition
* HOCs:

  * Structural abstraction
  * Legacy compatibility

### ❌ Weak Answer:

> “Hooks are better”

👉 Fails because:

* No explanation

***

## 13. What is a parameterized HOC and when is it useful?

### 🔍 Follow-up:

* Example?

### ✅ Strong Answer:

```js theme={null}
const withData = (url) => (Component) => { ... };
```

Use cases:

* Configurable behavior
* Reusable logic

### ❌ Weak Answer:

> “HOC with arguments”

👉 Fails because:

* No use-case clarity

***

## 14. How do HOCs interact with React.memo?

### 🔍 Follow-up:

* Can they break memoization?

### ✅ Strong Answer:

* Yes:

  * New props → re-render
* Need stable references

### ❌ Weak Answer:

> “They don’t affect”

👉 Fails because:

* Incorrect

***

## 15. What architectural problems arise from overusing HOCs?

### 🔍 Follow-up:

* How would you refactor?

### ✅ Strong Answer:

* Deep nesting
* Debugging difficulty
* Performance overhead

Refactor:

* Replace with hooks
* Flatten composition

### ❌ Weak Answer:

> “Too many components”

👉 Fails because:

* Too generic

***

## 16. How would you design a composable HOC system?

### 🔍 Follow-up:

* How do you avoid tight coupling?

### ✅ Strong Answer:

* Use composition helpers
* Keep HOCs focused
* Avoid side effects

```js theme={null}
compose(withAuth, withLogger)(Component)
```

### ❌ Weak Answer:

> “Combine them”

👉 Fails because:

* No structure

***

## 17. When can HOCs cause subtle bugs in async logic?

### 🔍 Follow-up:

* Example?

### ✅ Strong Answer:

* Race conditions in data fetching
* Stale closures
* Multiple instances triggering same fetch

### ❌ Weak Answer:

> “Async is tricky”

👉 Fails because:

* No concrete reasoning

***

## 18. How do you test a HOC?

### 🔍 Follow-up:

* What should be tested?

### ✅ Strong Answer:

* Test:

  * Props injection
  * Behavior changes
  * Rendering conditions

### ❌ Weak Answer:

> “Test UI”

👉 Fails because:

* Doesn’t test logic

***

## 19. When should you avoid HOCs entirely?

### 🔍 Follow-up:

* What’s the alternative?

### ✅ Strong Answer:

Avoid when:

* New codebases
* Complex logic reuse

Use:

* Custom hooks

### ❌ Weak Answer:

> “Never use HOCs”

👉 Fails because:

* Overgeneralization

***

# 🔚 Final Insight

At FAANG-level, HOCs are evaluated as:

* A **historical abstraction pattern**
* A **tool for structural composition**
* A **trade-off-heavy design choice**

***

👉 Strong candidates:

* Understand *why HOCs existed*
* Know *when to use or avoid them*
* Can *refactor them into modern patterns*

***
