Introduction to Higher Order Components (HOC) in React by Example

Mohan Dere
Jun 3, 2019 · 6 min read

If you’ve been using React for some time, you might have felt the need to have copies of the same logic in multiple components. A few use cases are:

  • Infinite scroll in three different views, all having different data
  • Components using data from third party subscription
  • App components that need logged in user data
  • Showing multiple lists(e.g. Users, Locations) with search feature
  • Enhancing different card views with same border and shadow

You might have wondered if there is a way in React to share logic across multiple components without having to rewrite it.

Well, you are right! There is an advanced technique to handle such cross-cutting concerns called Higher-Order Components (aka HOCs).

In this article, we will understand the HOCs in depth, when to use the pattern and cover different use cases with real-life examples.

Let’s start by understanding how this pattern evolved from functional programming.

Introduction to Functional Programming

One trend that has started gaining some serious traction in the past couple of years is functional programming (FP).

The traditional object-oriented approach encourages decomposition of a program into ‘objects’ that relate to a particular domain. In contrast, a functional approach guides the developer to decompose a program into small functions, which are then combined to form an application.

React and in fact, modern JS utilizes a lot of FP techniques alongside imperative code such as purity, side-effects, idempotent, function composition, closures, higher-order functions, currying, lazy evaluation etc.

Before moving further, I suggest you take a look at pure functions and side-effects from FP. This will prove helpful in understanding the basis of functional programming.

Let’s now delve into understanding higher order functions and higher order components with the help of examples.

A Taste of Higher-Order Functions in Functional Programming

A Higher-Order Function takes a function as an argument and/or returns a function.

React’s Higher Order Component is a pattern that stems from React’s nature that privileges composition over inheritance.

Consider this example -

What are Higher Order Components?

A higher-order component is a function that takes a component and returns a new component.

React’s Higher Order Component is a pattern that stems from React’s nature that privileges composition over inheritance.

Consider this example -

In the above example, higherOrderComponent is a function that takes a component called WrappedComponent as an argument. We have created a new component called HOC which returns the <WrappedComponent/> from its render function. While this actually adds no functionality, it depicts the common pattern that every HOC function will follow.

We can invoke the HOC as follows:

A higher-order component transforms a component into another component. Note that a HOC doesn’t modify the input component. Rather, a HOC composes the original component by wrapping it in a container component.

A HOC is a pure function with zero side-effects.

Coding a practical Higher-Order Component

Let’s say we want to create a list of products with a search feature. We would like to store our products array in a flat file and load it as a separate component as shown below -

Creating our first component

Let’s start by creating our first component ProductCard. This component is a functional component that handles the presentation of our data. The data (product) will be received via props, and each product will be passed down to the ProductCard component.

Rendering product list

Now, we need a component that will iterate over data (products) using map() function. Let’s call this component ProductsList.

This component will render the data in a ProductCard component.

Product list with search functionality

We want our users to be able to search for items using an input field. The list of items displayed on the app should be determined by the state of the search. This is a stateful component with user input stored in state value called searchTerm. Let’s call it ProductsListWithSearch.

The searchTerm is given a state of an empty string. The value entered by the user in the search box is obtained and used to set the new state for searchTerm.

Now what if we want to render a list of users with search functionality too?

We are going to create a new component similar to the one above. Let’s call it UsersListWithSearch.

Converting our ProductsListWithSearch into HOC

In the above code, we first imported the higher-order component. Then we added a filter method to filter the data based on what the user enters in the search input. Finally, we wrapped it with the withSearch component.

That’s it! We have a fully functional HOC in action!

Check out the complete example in the codepen below -

See the Pen React Hoc by Mohan Dere (@mohandere) on CodePen.

Debugging HOCs

Debugging HOCs can be hard as we can have multiple instances on the same HOC on the same page.

Let’s quickly compare the results with and without displayName prop in React Developer Tools.

Without displayName

With displayName

Caveats

Don’t use HOCs inside the render method

React’s reconciliation process uses component identity to decide whether it should update the existing subtree or mount a new one between two renders. This means component identity should be consistent across renders.

Also, when a component’s state changes, React has to calculate if it is necessary to update the DOM. It does this by creating a virtual DOM and comparing it with the current DOM. In this context, the virtual DOM will contain the new state of the component.

If you are using HOCs inside the render method, then the identity of HOCs cannot be preserved across render and that affects the overall app performance.

But the problem here isn’t just about performance — remounting a component causes the state of that component and of all of its child components to be lost.

Instead, we should apply HOCs outside the component definition so that the resulting component is created only once.

Static methods must be copied over

Using static method on a React component isn’t useful especially if you want to apply HOC on it. When you apply a HOC to a component, it returns a new enhanced component. In effect, the new component does not have any of the static methods of the original component.

To solve this, you could use hoist-non-react-statics to automatically copy all non-React static methods:

Refs are not passed through

You may want to pass all props to the wrapped component. However, you need to pay attention to refs since they are not passed through. This is because ref is not really a prop — like key, it’s handled specially by React.

The solution for this problem is to use the React.forwardRef API.

Conclusion

At the most basic level, React Higher-Order Component is the function that returns a class and is the implementation of functional programming principles in your codebase. It is also possible to pass higher order components into other higher order components since typically they take components as input and return other components as output. This can introduce unnecessary nesting into your component tree though.

Libraries such as Redux’s connect, react-router’s withRouter are good examples of why we should think about implementing higher order components.

We use higher order components to primarily reuse logic in React apps. However, they have to render some UI. Hence, HOCs are inconvenient when you want to share some non-visual logic. In such a case, React hooks seem to be a perfect mechanism for code reuse.

Originally published at https://blog.flexiple.com on June 3, 2019.

Connecting top tech talent with startup & companies.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store