SmartCodingTips

πŸŒ€ Higher-Order Components (HOC)

A Higher-Order Component (HOC) is a function that takes a component and returns a new component with added functionality. It's a pattern for reusing component logic.


πŸ“˜ 1. What is an HOC?

An HOC is a **pure function** β€” it doesn’t modify the input component, but returns a new one. Common use cases include authentication, logging, conditional rendering, and more.

πŸ§ͺ 2. Example: WithLoading HOC


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

βš™οΈ 3. Usage


function UserList({ users }) {
  return (
    <ul>
      {users.map(u => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

const UserListWithLoading = withLoading(UserList);

// In App:
<UserListWithLoading isLoading={false} users={userData} />

βœ… 4. Why Use HOCs?

  • Logic reuse across components
  • Separation of concerns
  • Can wrap components without altering their structure

πŸ’‘ 5. Best Practices

  • Use descriptive HOC names (e.g. withAuth, withLogging)
  • Do not mutate the original component
  • Pass props transparently with {...props}
  • Avoid unnecessary nesting and complexity

⚠️ 6. Drawbacks

  • Can lead to "wrapper hell" (too many nested components)
  • Less intuitive than hooks for some cases
  • Hooks are generally preferred in modern React