Higher Order Component(HOC) design pattern in React.

Harshwardhan Rathore
Frontend Weekly
Published in
2 min readDec 27, 2017

This post is about how you can make use of HOC design pattern to write better code which is easy to maintain and understand even by a new developer.

Topics we are going to cover in this post:

  1. What are HOC and how to write one?
  2. What are the benefits of following HOC pattern?

In this post I will explain the above to points with a real world example. We are going to write a small feature (Login form).

So what is Higher Order Component? A Higher order component is a function that takes a component as an argument and returns a new component.

Consider you are writing a user login feature for your awesome app. So you will write something like this.

For the sake of simplicity I am not doing any client side validation but you should do it, there is no excuse for not doing it.

As you can see the representation part of this form is just a form with two input fields and a submit button.

Now consider a situation where you have to add exact same functionality but with different ui in a different part of your app. You would like to re-use this component but the representation is entirely different.

How would you solve that problem? Chances are you might end up creating two stateless component for the two forms and pass the handlers as props to these components, which is a right approach to go with but that doesn’t look so clean does it? Have a look how can we solve the same problem with an HOC.

and that’s it. Now it doesn’t matter how many login forms you need in you app you just need to wrap that new shiny login form with this `LoginHOC` and you will have access to all the props that you are passing from HOC. Even if there is some other feature that you want to add you have to add it in your LoginHOC and everything will work just fine.

If you are following any other pattern to tackle the same problem, you should try using HOC pattern in your app and I am sure you won’t regret it.

Thanks for reading now make something great :).

--

--