What is a HOC?

Higher Order Component (HOC) is a function which accepts a base component and returns a decorated component.

The component that the HOC returns is a stateless functional component. At its most basic form, the base component is rendered with all the supplied props. The props can be overridden by a variation of HOC which accepts an option or configuration.

The above HOC accepts a configuration which is more props.

Recompose

Recompose provides several higher order components which can be part of your React toolbox. I first came across the library while doing an enhancement for react-infinite-calendar. Since then, I have been a prolific user, using wherever it makes sense.

It is common to come across a list component in our apps. Consider a list of Order items Orders. Each order item has an order id and status. The status can be one of ‘Placed’, ‘Shipped’, ‘Delivered’. Usually, we want to filter the list by order status. We usually filter the orders and pass it to the Orders component.

With a HOC, the component can be rewritten as follows:

The filtering logic is moved to a HOC which uses mapProps. mapProps takes a props object and returns a new props object. We filter the items prop. In addition, we insert a new status prop. Our HOC is not of much use if we cannot refactor reusable code.

The above code illustrates the elegance of recompose. And how the HOC extracts reusable code.

Using Recompose for writing elegant Higher Order Components
Tagged on:     

Leave a Reply

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