What Are React Higher-Order Components? See Example

What Are Higher-Order Components (HOC)?

A Higher-Order Component (HOC) is a function that takes a component and returns a new component.
It is used to reuse component logic without repeating code.


Basic Syntax

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Example: Adding Props via HOC

import React from "react";

function withUser(WrappedComponent) {
  return function Enhanced(props) {
    const user = { name: "Sagar" };
    return <WrappedComponent user={user} {...props} />;
  };
}

function DisplayUser({ user }) {
  return <h2>User Name: {user.name}</h2>;
}

const EnhancedDisplayUser = withUser(DisplayUser);

function App() {
  return <EnhancedDisplayUser />;
}

✅ HOC injects user prop into DisplayUser dynamically.


Key Points

  • HOC is not a component itself, it returns one
  • Helps reuse logic like authentication, tracking, theming
  • Can wrap multiple components
  • Keep HOCs pure and composable

Conclusion

React HOCs allow code reuse and modular logic, enhancing maintainability and reducing duplication across components.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *