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 Case | HOC Example |
|---|---|
| Auth Protection | withAuth(Component) |
| Logging | withLogger(Component) |
| Theme Injection | withTheme(Component) |
| Reusable Layout | withLayout(Component) |
| Error Handling | withErrorBoundary(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
withXyzconvention. - Avoid mutating the original component.
- Preserve static methods using libraries like
hoist-non-react-statics.
π Summary
| Concept | Description |
|---|---|
| What is HOC | A function that returns a new component |
| Purpose | Logic reuse (auth, logging, theming) |
| Syntax | const NewComp = withSomething(OrigComp) |
| Common use cases | Auth, theming, logging, layout |
Advertisement Slot 1
Advertisement Slot 2