Higher-Order Components

Subject: React

What is a Higher-Order Component (HOC)?

A Higher-Order Component is a function that takes a component and returns a new component with additional features or logic.

πŸ“Œ HOCs are used to reuse component logic (e.g., auth protection, theming, data fetching) across multiple components.


πŸ“¦ Basic Syntax

  • WrappedComponent: The original component.
  • withExtraLogic: HOC function that returns a new component.

πŸ§ͺ Example: Basic HOC (Logging Props)

πŸ”§ Usage:


πŸ›‘οΈ Example: Auth Guard using HOC

πŸ” 1. Create HOC

πŸ§‘β€πŸ’» 2. Create a Protected Page

πŸ§ͺ 3. Wrap with HOC

βœ… 4. Use in App


πŸ” Real-World Use Cases

Use CaseHOC Example
Auth ProtectionwithAuth(Component)
LoggingwithLogger(Component)
Theme InjectionwithTheme(Component)
Reusable LayoutwithLayout(Component)
Error HandlingwithErrorBoundary(Component)

⚠️ Caveats

  • HOCs don’t work with Hooks inside the HOC function directly β€” hooks must obey React rules inside functional components.
  • Prop name collisions: be careful when injecting or modifying props.
  • Wrapper Hell: nesting many HOCs can complicate debugging.

βœ… Best Practices

  • Name HOCs with withXyz convention.
  • Avoid mutating the original component.
  • Preserve static methods using libraries like hoist-non-react-statics.

πŸ”š Summary

ConceptDescription
What is HOCA function that returns a new component
PurposeLogic reuse (auth, logging, theming)
Syntaxconst NewComp = withSomething(OrigComp)
Common use casesAuth, theming, logging, layout