Skip to main content

๐Ÿ“˜ 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
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

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:
const Enhanced = withFeature(Component);
Internally:
function Enhanced(props) {
  return <Component {...props} extraProp="value" />;
}

๐Ÿ”น 3. Props Forwarding

Critical concept:
  • HOC must pass original props
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:
WrappedComponent.prototype.componentDidMount = ...
๐Ÿ‘‰ Never mutate the original component

๐Ÿ”น 6. Relationship with Other Patterns

PatternRelationship
Render PropsAlternative for logic reuse
HooksModern replacement for most HOCs
ContextOften used inside HOCs
CompositionHOCs are composition-based

๐Ÿ”น 7. How React Handles HOCs Internally

React treats:
<EnhancedComponent />
As:
  • A normal component
  • Wrapper renders inner component
๐Ÿ‘‰ No special optimization โ€” just nested components

3. ๐Ÿงช Syntax & Examples


๐Ÿ”น Basic HOC Example

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

Usage:

const LoggedComponent = withLogger(MyComponent);

๐Ÿ”น Example: Authentication HOC

function withAuth(WrappedComponent) {
  return function Enhanced(props) {
    const isLoggedIn = true;

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

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

๐Ÿ”น Example: Data Fetching HOC

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:

const UserComponent = withData("/api/user")(User);

๐Ÿ”น Example: Conditional Rendering HOC

function withLoading(WrappedComponent) {
  return function ({ isLoading, ...props }) {
    if (isLoading) return <p>Loading...</p>;
    return <WrappedComponent {...props} />;
  };
}

๐Ÿ”น Composing Multiple HOCs

const Enhanced = withAuth(withLogger(MyComponent));

๐Ÿ”น Variation: Using Utility Composition

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

return <WrappedComponent />; // โŒ
๐Ÿ‘‰ Props lost โœ… Fix:
return <WrappedComponent {...props} />;

๐Ÿ”น 2. Mutating Wrapped Component

WrappedComponent.someMethod = ... // โŒ
๐Ÿ‘‰ Breaks component integrity

๐Ÿ”น 3. Losing Static Methods

MyComponent.staticMethod = () => {};
HOC removes it โŒ

โœ… Fix:

import hoistNonReactStatics from "hoist-non-react-statics";

hoistNonReactStatics(Enhanced, WrappedComponent);

๐Ÿ”น 4. Ref Not Forwarded

<Enhanced ref={ref} /> // โŒ doesn't work

โœ… Fix:

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

๐Ÿ”น 5. Wrapper Hell

withA(withB(withC(Component)))
๐Ÿ‘‰ Hard to debug

๐Ÿ”น 6. Props Collision

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

<WrappedComponent {...props} />

๐Ÿ”น 2. Use Clear Naming

withAuth
withLogger
withData

๐Ÿ”น 3. Set Display Name

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

return React.memo(Enhanced);

๐Ÿ”น 7. Avoid Deep Nesting

โœ” Use composition helpers

๐Ÿ”น 8. Use ForwardRef When Needed

React.forwardRef(...)

๐Ÿ”น 9. Prefer Hooks for New Code

๐Ÿ‘‰ Modern React: โŒ HOC:
const Enhanced = withData(Component);
โœ” Hook:
const data = useData();

๐Ÿ”น 10. Keep HOCs Focused

โŒ Bad:
withEverything()
โœ” Good:
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:
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
const Enhanced = withFeature(Component);
Internally:
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

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

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

๐Ÿ’ก Why:

  • HOC sits between parent and wrapped component
  • Without forwarding โ†’ props are lost

๐Ÿ”ด Failure case:

return <WrappedComponent />; // โŒ
๐Ÿ‘‰ Breaks component contract

5. What is โ€œwrapper hellโ€ in HOCs, and how does it affect architecture?

โœ… Answer

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:

return React.memo(Enhanced);

7. Why do HOCs often cause prop name collisions?

โœ… Answer

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

Component.fetchData = () => {};
After wrapping:
const Enhanced = withHOC(Component);
๐Ÿ‘‰ Static method is lost โŒ

๐Ÿ’ก Why:

New component doesnโ€™t inherit statics

๐ŸŸข Fix:

hoistNonReactStatics(Enhanced, Component);

9. Why donโ€™t refs work directly with HOCs?

โœ… Answer

<Enhanced ref={ref} /> // โŒ

๐Ÿ’ก Why:

Ref attaches to wrapper, not inner component

๐ŸŸข Fix:

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

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

โœ… Answer

AspectHOCRender Props
StructureWrapperInline function
FlexibilityLimitedHigh
ReadabilityBetter (initially)Degrades with nesting
DebuggingHardEasier

๐Ÿ’ก 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

AspectHOCHooks
ReadabilityLowerHigher
NestingWrapper hellFlat
PerformanceExtra layersBetter
FlexibilityStructuralFunctional

๐Ÿ’ก 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:

export default withAuth(withLogger(Component));

13. How would you design a reusable HOC API?

โœ… Answer

Principles:
  • Minimal API
  • Clear naming
  • No side effects
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:

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:
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

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

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:
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:

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:

<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?

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:

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

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

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

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

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

return function Enhanced(props) {
  console.log("render");
  return <Wrapped {...props} />;
};

๐Ÿง  Best Practice

Always forward all props unless intentionally filtering.

2. โ— Static Methods Lost

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

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

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

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

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

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

๐Ÿง  Best Practice

Never update state inside render phase.

5. โ— Prop Collision

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

return <Wrapped {...props} injectedUser="admin" />;

๐Ÿง  Best Practice

Namespace injected props to avoid collisions.

6. โ— Unstable Object Causing Re-renders

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

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

๐Ÿง  Best Practice

Memoize objects/functions passed as props.

7. โ— Event Listener Leak

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

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

useEffect(() => {
  fetchData();
}, []); // โŒ ignoring props.url

๐Ÿ” Whatโ€™s wrong?

Effect does not respond to prop changes.

๐Ÿ’ก Why

Missing dependency โ†’ stale data.

โœ… Fix

useEffect(() => {
  fetchData();
}, [props.url]);

๐Ÿง  Best Practice

Always include external dependencies.

9. โ— Mutating Props

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

return <Wrapped {...props} value="changed" />;

๐Ÿง  Best Practice

Never mutate props.

10. โ— Missing Display Name

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

๐Ÿ” Whatโ€™s wrong?

Hard to debug in DevTools.

๐Ÿ’ก Why

Component appears as anonymous.

โœ… Fix

Enhanced.displayName = `withFeature(${Wrapped.displayName || Wrapped.name})`;

๐Ÿง  Best Practice

Always set displayName.

11. โ— Over-fetching Data

useEffect(() => {
  fetch("/api").then(setData);
}); // โŒ no dependency

๐Ÿ” Whatโ€™s wrong?

Runs on every render.

๐Ÿ’ก Why

Missing dependency array.

โœ… Fix

useEffect(() => {
  fetch("/api").then(setData);
}, []);

12. โ— Wrapper Hell Performance Issue

export default withA(withB(withC(Component)));

๐Ÿ” Whatโ€™s wrong?

Deep nesting โ†’ performance + readability issues.

๐Ÿ’ก Why

Each layer adds render overhead.

โœ… Fix

const Enhanced = compose(withA, withB, withC)(Component);

๐Ÿง  Best Practice

Flatten composition or use hooks.

13. โ— Async Race Condition

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

๐Ÿ” Whatโ€™s wrong?

Older requests may override newer ones.

๐Ÿ’ก Why

Async calls resolve out of order.

โœ… Fix

useEffect(() => {
  let active = true;

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

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

14. โ— Breaking Memoization

return <Wrapped {...props} onClick={() => doSomething()} />;

๐Ÿ” Whatโ€™s wrong?

New function each render.

๐Ÿ’ก Why

Breaks React.memo.

โœ… Fix

const handleClick = useCallback(() => doSomething(), []);

15. โ— Conditional Hook Usage Inside HOC

if (props.enabled) {
  useEffect(() => {});
}

๐Ÿ” Whatโ€™s wrong?

Violates Rules of Hooks.

๐Ÿ’ก Why

Hooks must run in same order.

โœ… Fix

useEffect(() => {
  if (props.enabled) { }
}, [props.enabled]);

16. โ— Recreating HOC Inside Render

function Parent() {
  const Enhanced = withFeature(Component); // โŒ
  return <Enhanced />;
}

๐Ÿ” Whatโ€™s wrong?

New component created every render.

๐Ÿ’ก Why

Breaks React identity โ†’ remounts component.

โœ… Fix

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

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

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

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
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
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:
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
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
<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:

HOCRender Props
StructuralDynamic UI
Wrapper nestingCallback nesting
Less flexibleMore 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:

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