Top 5 Recompose HOCs

Abhi Aiyer
3 min readMay 27, 2017

Recompose by Andrew Clark has really changed the way my team and I develop React components. If you haven’t used this library, it provides an assortment of higher order components giving the engineer a very “lodash” like developer-experience.

For more details on Composition in React, I’d take a look at Nik Graf‘s React Europe talk:

Today we’ll be going through my 5 (in no particular order) favorite Recompose Higher Order Components:

1. branch

Ever have a decision tree which based on a condition, your component behaves differently? Branch is a great way to do that logic split and decorate your BaseComponent with a higher order component.

The great thing here is your test function receives props from the owner. If our test function returns true, the Headline HOC is applied to the Example component; otherwise, the Paragraph HOC is applied.

2. mapProps

mapProps is great for situations when in conjunction with another HOC you want to return some “derived” props. mapProps allows you to write a function that maps the current props and returns a NEW collection of props to the BaseComponent. My favorite use case is with the graphql HOC from react-apollo.

You will notice the compose HOC above. This allows us to combine different HOCs together into one big Component. It’s like VOLTRON.

We combine the withRouter HOC from react-router, this passes the route context via props to the BaseComponent. We then use the graphql container from react-apollo to make a GraphQL query to our backend and return the results to the component via props.

We then use mapProps to make a new set of props. In this case we grab the job data, and total count to return new props to the component using this container.

3. withState + withHandlers