π 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