A higher-order component is a pattern that can be created with the React components. We can pass the reusable logic as props to the functional components to implement abstraction, reusability, and uniformity in the code.

The principles of OOPS are embedded deep in the programming and in one way or another using them helps to make the code more readable, and less verbose and promotes reusability.

A higher-order component (HOC) is a pattern that emerges in React given its compositional nature, where we can pass one component to another component as an argument, and this parent component (Higher-order) will have certain logic that it will pass down to this received component as props.

For example, if you worked with Redux, you will notice how we use the connect() HOC to compose the components with the states and the actions.

const ConnectedUsersList = connect(usersSelector, usersActions)(UsersList);

Here the connect() method receives two arguments and returns another function that accepts the UsersList as arguments forming a composition of components.

Now in the UsersList, you will receive the states and the actions as props.

This can be written more discretely as,

// create a connection first
const connectRedux = connect(usersSelector, usersActions);

// then connect the component
const ConnectedUsersList = connectRedux(UsersList);

This helps to abstract all the logic at the single place in the connect() method making it a single source of truth and all the components passing through it will receive similar props for the same inputs making it a pure higher-order component function.

This pattern is really helpful when you want to abstract the common logic in a single place.

For example, let's say you have a product list website with different categories.

We can create a product component that will receive the list of the products as props and will display it.

const ProductsList = ({ data }) => {
  return data.map((e) => (
    <div key={e.id} className="product-item">
      <h2>Item: {e.title}</h2>
    </div>
  ));
};

Assuming that we have a uniform response for all the API’s for every category, we can create a higher-order component that will take the API URL and the products list component input and will fetch the data and pass it to the products list to display.

This higher-order component will maintain the loading and the error state logic abstracting everything making the product list independent to just show the list without worrying about anything.

To create an HOC we follow a naming convention starting the function name with with keyword like withFetchData().

This is a functional component that will take an argument and return another function from it forming a closure.