Design Patterns in React(Part II) : The Higher Order Component Pattern

Żimuzo Obiechina
2 min readFeb 16, 2020

--

Buildings connected by a sky bridge.
Photo by Mitchell Luo on Unsplash

This post is a part of this series on Design Patterns in React.

In the wise words of William of Ockham, “it is futile to do with more things that which can be done with fewer…”; a statement which I dare say,succinctly sums up the concept of the Higher-Order-Component(HOC) Pattern.

Higher-Order-Component Pattern

This pattern is a concept derived from higher-order functions. An HOC is basically a function that takes another component as input and returns an enhanced component as output.

const HOC = Component => EnhancedComponent;

To understand why we need higher-order components, let’s consider a scenario where multiple components in an application retrieve data from the same API and display the data in a similar fashion. In the first part of the example below, let’s say the UserProfile class component from this previous post needs to be expanded to display posts associated with the user by getting the data from an API:

But, we also want to display a list of users, so we create another component called UserList:

Now, what if we want to have other components in this same application that perform the same task? That will mean replicating this code for each component! That is less than ideal. Remember the DRY principle?

Cue in higher-order components! What an HOC will do is wrap the functionality/task to be performed, in a function, so that any component passed in as an argument is ‘wrapped’ by this function/component, and then returns a version that automatically gives the passed in component access to the functionality.

To demonstrate this, let’s create a higher order component that can take in any component as an argument, along with the source url for data-fetching:

Do you notice how it has isolated the functionality shared by these components and made it generic? With this HOC pattern in place, we’ll need to modify our initial code. We will convert the UserProfile class component into a functional component, which is then wrapped into the withData HOC, and exported:

The same pattern is applied to the UserList component:

As you can see, this modification has exponentially improved the maintainability potential of the codebase. This pattern leverages the composition model of React, allowing for easier debugging.

A practical example of the HOC in React is the withRouter HOC, which passes to its argument access to the match, location and history objects; useful for navigating through an application. You can learn more about it here.

Thank you for reading!

--

--