QA
Beginner LevelReact JS & React 19

What is a Higher-Order Component (HOC) and how does it compare to custom hooks?

❓ Interview Prompt: Explain Higher-Order Components (HOC), component wrapping pattern (`withAuth(Profile)`), prop injection, and custom hook replacement.

A Higher-Order Component (HOC) is an advanced pattern in React for reusing component logic. An HOC is a function that takes a component and returns a new enhanced component:

HOC vs Custom Hooks:

•
HOC ('const ProtectedPage = withAuth(Profile)'): Wraps component tree, injecting props. Can lead to "wrapper hell" and obscured prop origins.
•
Custom Hooks ('useAuth()'): Modern preferred pattern. Shares stateful logic directly inside component bodies cleanly without nesting wrapper nodes.

Code Implementation Example

jsx
// Higher-Order Component pattern
function withAuthentication(WrappedComponent) {
  return function AuthenticatedComponent(props) {
    const { isAuthenticated } = useAuth();
    if (!isAuthenticated) return <p>Please Log In</p>;
    return <WrappedComponent {...props} />;
  };
}

// Usage:
const ProtectedDashboard = withAuthentication(Dashboard);
💡Wrapping components with Higher-Order Component logic.
🎯 Interview Key Takeaway

Higher-Order Components wrap components to inject logic; custom hooks are preferred in modern React for cleaner composition.

#HOC#Higher-Order Components#Patterns#Beginner
Back to all React JS & React 19 Questions→

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?