Decorator Power: Reusing Logic with Higher-Order Components

Wrap a component to inject features like loading states, auth, or logging. HOCs help avoid repeating logic across many components. Great for legacy/class components, but hooks are now preferred.

A Higher-Order Component (HOC) is a function that takes a component and returns a new component with extra powers.

👉 Think of it like wrapping a gift — the inside (your component) stays the same, but you decorate it with new features.

Basics & Need

Sometimes multiple components need shared behavior (e.g., logging, authentication, data fetching). Instead of duplicating logic everywhere, you create an HOC to wrap components and inject that behavior.

How to Achieve It

// HOC: withLogger
const withLogger = (WrappedComponent) => {
return (props) => {
console.log("Props received:", props);
return <WrappedComponent {...props} />;
};
};

// Usage
const Button = (props) => <button>{props.label}</button>;

const LoggedButton = withLogger(Button);

// Render
<LoggedButton label="Click Me" />;

👉 Button doesn’t know it’s being logged.
👉 withLogger adds cross-cutting concern (logging).

Best Practices

  • Always pass down props ({...props}) so the wrapped component stays reusable.
  • Use descriptive names (withAuth, withTheme) to make intent clear.
  • Keep HOCs pure — don’t modify the original component.
  • Compose multiple HOCs instead of stuffing too much into one.

Real-World Examples

  1. Authentication GatewithAuth(Component) to block unauthorized users.
  2. ThemingwithTheme(Component) injects theme props.
  3. AnalyticswithTracker(Component) logs usage data.

Advantages

  • Reusable: share logic across many components.
  • Declarative: wrap features without touching component internals.
  • Great for cross-cutting concerns (auth, logging, analytics).

Disadvantages

  • Wrapper Hell: multiple nested HOCs can make debugging hard.
  • Harder to follow React DevTools tree (lots of “Anonymous” components).
  • Modern React often prefers Hooks & custom hooks over HOCs.

Common Problems / Pitfalls

  • Forgetting to forward ref → breaks focus or DOM access.
  • Prop name collisions when injecting new props.
  • Wrapping a component too many times → performance & readability issues.

Summary Recommendation

Use HOCs when you need to add behavior across many components (e.g., authentication, theming, analytics). They shine in large apps where logic reuse is critical. But in modern React, prefer Hooks unless you specifically need HOCs (like when integrating with class components or legacy code).