← Back to Chapters

Higher-Order Components

? Higher-Order Components

? Quick Overview

A Higher-Order Component (HOC) is an advanced React pattern used to share and reuse logic between components. Instead of duplicating code, a HOC wraps an existing component and returns a new enhanced component.

HOCs are commonly used for concerns that affect many components in the same way, such as authentication, logging, performance tracking, permissions, and theming.

? Key Concepts

  • Function-based: HOCs are functions that accept a component and return another component.
  • Logic reuse: Helps avoid repeating the same logic in multiple components.
  • Non-mutating: The original component is never modified.
  • Composable: Multiple HOCs can be combined together.
  • Transparent: Wrapped components should still receive all their original props.

? Syntax / Theory

A HOC follows a predictable structure: take a component, wrap it, and return a new component with added behavior.

? View Code Example
// Generic HOC syntax
const EnhancedComponent = higherOrderComponent(WrappedComponent);

This pattern allows React to treat the enhanced component like any normal component.

? Basic Example: Logging Props

This example demonstrates a simple HOC that logs props whenever the wrapped component renders.

? View Code Example
// HOC that logs incoming props
function withLogger(WrappedComponent) {
return function Enhanced(props) {
console.log("Props received:", props);
return <WrappedComponent {...props} />;
};
}

The wrapped component remains unchanged, while logging behavior is injected externally.

⚙️ Real-World Example: Authentication

Authentication is a classic use case for HOCs. Protected components should only render if a user is logged in.

? View Code Example
// HOC that blocks access for unauthenticated users
function withAuth(WrappedComponent) {
return function Authenticated(props) {
const isLoggedIn = localStorage.getItem("user");
if (!isLoggedIn) {
return <h4>Access Denied</h4>;
}
return <WrappedComponent {...props} />;
};
}

This keeps authentication logic separate from UI components like dashboards or profiles.

? HOC Composition

Multiple HOCs can be layered together to apply several behaviors in a clean and readable way.

? View Code Example
// Applying authentication first, then logging
const Enhanced = withLogger(withAuth(Dashboard));

Execution happens from right to left: DashboardwithAuthwithLogger.

? Passing Props Correctly

A well-written HOC must always forward props, otherwise the wrapped component may break.

? View Code Example
// Forwarding all props to the wrapped component
function withBorder(WrappedComponent) {
return function Enhanced(props) {
return (
<div style={{ border: "2px solid gray", padding: "10px" }}>
<WrappedComponent {...props} />
</div>
);
};
}

? Live Explanation

When a component is wrapped by a HOC, React renders the outer component first. The HOC executes its logic, then renders the original component with the same props plus any enhancements.

? Tips & Best Practices

  • Prefix HOC names with with for clarity.
  • Always forward props using {...props}.
  • Set a descriptive displayName for easier debugging.
  • Avoid creating HOCs inside render functions.
  • Prefer Hooks for new projects, but understand HOCs conceptually.

? Try It Yourself

  1. Create a withTheme HOC that injects a theme prop.
  2. Use the prop to conditionally style a Button component.
  3. Combine it with withLogger to track renders.
  4. Log the enhanced component’s displayName.

Goal: Understand how Higher-Order Components enable reusable, composable logic in React.