Advertisement
  1. Code
  2. JavaScript
  3. React

A Gentle Introduction to Higher-Order Components in React

Scroll to top
9 min read
This post is part of a series called A Gentle Introduction to Higher Order Components in React.
A Gentle Introduction to HOC in React: Learn by Example
A Gentle Introduction to Higher-Order Components in React

Higher-Order Components (HOCs) are an interesting technique in React used to refactor similar components that share almost the same logic. I know that it sounds abstract and advanced. However, it is an architectural pattern that isn't specific to React, and hence you can use the approach to do lots of things. 

For instance, you could use it to add a loading indicator to a certain component without tweaking the original component, or you could hide a component's props to make it less verbose. The applications are many, and I've tried to cover most of them in this tutorial.

There are several other tutorials that teach you about HOCs, but most of them are meant for advanced React developers. When I started learning React, I had trouble understanding the concept of higher-order components and how I could incorporate HOCs in my project to write better code. This article will explain everything that you need to know about HOC from scratch to hatch. 

Overview

This tutorial is split into three parts. The first part will serve as an introduction to the concept of higher-order components. Here, we shall talk about the syntax you need to know before looking at higher-order functions and HOCs. The second part is the most exciting part of this series where you will see practical examples of HOCs. We will use HOCs for creating forms, authorization, and many other things. 

In the third part of this tutorial, we will focus more on best practices and things to consider while implementing higher-order components. We will also have a brief look at alternative patterns for code sharing in React, such as Render props.

Before getting started, it might be a good idea to take a look at the tutorial on Stateful vs. Stateless components to understand React's component architecture better.

ES6 Syntax Cheatsheet

We will get our hands dirty soon. But before we do, here are some things that I think you should know about. I prefer to use the ES6 syntax wherever possible, and it works great with HOCs. As a beginner, HOC made sense, but some of the ES6 syntax did not. So I recommend going through this section once, and you can come back here later for reference. 

Arrow Functions

Arrow functions are regular function expressions, but with shorter syntax. They are best suited for non-method functions, and that's what we are particularly interested in. Here are some examples to get you started:

Function Without Parameters

1
/* Functions without parameters */
2
function () {
3
    return "This is a function expression";
4
}
5
6
// is equivalent to

7
8
() => {
9
 return "This is an arrow function expression"
10
}
11
12
// or 

13
14
() => "Arrow with a shorter syntax"

Function With a Single Parameter

1
/* Function with a single parameter */
2
3
function (param) {
4
  return { title: "This function accepts a parameter and returns an object",
5
          params: param}
6
}
7
8
// is syntax-equivalent to 

9
10
param => {
11
    return { title: "This arrow function accepts a single parameter",
12
        params: param }
13
}
14

Function With Multiple Parameters

1
/* Function with multiple parameters */
2
3
function (param1, param2) {
4
  return { title: "This function accepts multiple parameters",
5
          params: [param1,param2]}
6
}
7
8
// is syntax-equivalent to 

9
10
(param1, param2) => {
11
    return {title: "Arrow function with multiple parameters",
12
    params: [param1, param2]
13
    }
14
}
15
16
// or

17
18
(param1, param2) => ({
19
      title: "Arrow function with multiple parameters",
20
    params: [param1, param2]
21
    })

Currying in Functional Programming

Although the name suggests that it has something to do with an exotic dish from the popular Indian cuisine, it doesn't. Currying helps you break down a function that takes many arguments into a series of functions that take one argument at a time. Here is an example:

1
//Usual sum function

2
const sum = (a, b) => a + b
3
4
//Curried sum function 

5
const curriedSum = function (a) {
6
    return function (b) {
7
        return a+b
8
    }
9
10
//Curried sum function using arrow syntax

11
const curriedSum = a => b => a+b
12
13
curriedSum(5)(4)
14
//9

The function accepts just one argument and returns a function that takes in another argument, and this continues until all the arguments are satisfied. 

1
curriedSum
2
// (a) => (b) => a+b

3
4
curriedSum(4)
5
6
// (b) => 4+b

7
8
curriedSum(4)(5)
9
10
//4+5

A closely related term is called partial application. The partial application deals with creating a new function by pre-filling some of the arguments of an existing function. The newly created function will have an arity (which translates to the number of arguments) less than that of the original function.

Spread Syntax

Spread operators spread the contents of an array, string, or object expression. Here is a list of stuff that you can do with spread operators

Spread Syntax in Function Calls

1
/*Spread Syntax in Function Calls */
2
const add = (x,y,z) => x+y+z
3
4
const args = [1,2,3]
5
6
add(...args) 
7
// 6

8

Spread Syntax in Array Literals

1
/* Spread in Array Literals */
2
3
const twoAndThree = ['two', 'three']; 
4
const numbers = ['one', ...twoAndThree, 'four', 'five']; 
5
// ["one", "two", "three", "four", "five"]
6

Spread Syntax in Object Literals

1
/* Spread in Object Literals */
2
3
const contactName = {
4
  name: {
5
    first: "Foo",
6
    middle: "Lux",
7
    last: "Bar"
8
  }
9
}
10
const contactData = {
11
  email: "fooluxbar@example.com",
12
  phone: "1234567890"
13
}
14
15
const contact = {...contactName, ...contactData}
16
/* { 

17
    name: {

18
        first: "Foo",

19
        middle: "Lux",

20
        last: "Bar"

21
    }

22
    email: "fooluxbar@example.com"

23
    phone: "1234567890"

24
  }

25
  

26
*/
27
        

I personally love the way in which three dots can make it easier for you to pass down existing props to child components or create new props.

Spread Operator in React

1
const ParentComponent = (props) => {
2
  const newProps = { foo: 'default' };
3
  
4
  return (
5
      <ChildComponent 
6
  		{...props} {...newProps} 
7
  	/>

8
  )
9
}

Now that we know the basic ES6 syntax for building HOCs, let see what they are.

Higher-Order Functions

What is a higher-order function? Wikipedia has a straightforward definition:

In mathematics and computer science, a higher-order function (also functional, functional form or functor) is a function that either takes one or more functions as arguments or returns a function as its result or both.

You've probably used a higher-order function in JavaScript before in one form or another because that's the way JavaScript works. Passing anonymous functions or callbacks as arguments or a function that returns another function—all this falls under higher-order functions. The code below creates a calculator function which is higher order in nature. 

1
const calculator = (inputFunction) => 
2
    	(...args) => {
3
        
4
       const resultValue = inputFunction(...args);
5
       console.log(resultValue);
6
          
7
       return resultValue;
8
        }
9
10
const add = (...all) => {
11
	return all.reduce( (a,b) => a+b,0)	;
12
  
13
	}
14
  
15
 
16
const multiply = (...all) => {
17
  return all.reduce((a,b)=> a*b,1);
18
 
19
  }

Let's have a deeper look at this. The calculator() accepts a function as input and returns another function—this perfectly fits into our definition of a higher-order function. Because we've used the rest parameter syntax, the function returned collects all its arguments inside an array. 

Then, the input function is invoked with all the arguments passed down, and the output is logged to the console. So the calculator is a curried, higher-order function, and you can use your calculator like this:

1
calculator(multiply)(2,4);
2
// returns 8

3
4
calculator(add)(3,6,9,12,15,18); 
5
// returns 63

Plug in a function such as add() or multiply() and any number of parameters, and calculator() will take it from there. So a calculator is a container that extends the functionality of add() and multiply(). It gives us the ability to deal with problems at a higher or more abstract level. At a glance, the benefits of this approach include:

  1. The code can be reused across multiple functions.
  2. You can add extra functionality common to all arithmetic operations at the container level. 
  3. It's more readable, and the intention of the programmer is better expressed.

Now that we have a good idea about higher-order functions, let's see what higher-order components are capable of.

Higher-Order Components

A higher-order component is a function that accepts a component as an argument and returns an extended version of that component. 

1
(InputComponent) => {
2
    return ExtendedComponent 
3
    }
4
    
5
// or alternatively

6
7
InputComponent => ExtendedComponent
8

The ExtendedComponent composes the InputComponent. The ExtendedComponent is like a container. It renders the InputComponent, but because we're returning a new component, it adds an extra layer of abstraction. You can use this layer to add state, behavior, or even style. You can even decide not to render the InputComponent at all if you desire—HOCs are capable of doing that and more.

The image below should clear the air of confusion if any.

Higher Order Components Overview Higher Order Components Overview Higher Order Components Overview

Enough with the theory—let's get to the code. Here is an example of a very simple HOC that wraps the input component around a <div> tag. From here on, I will be referring to the InputComponent as WrappedComponent because that's the convention. However, you can call it anything you want.

1
/* The `with` prefix for the function name is a naming convention.

2
You can name your function anything you want as long as it's meaningful 

3
*/
4
5
const withGreyBg = WrappedComponent => class NewComponent extends Component {
6
  
7
  const bgStyle = {
8
  		backgroundColor: 'grey',
9
	};
10
    
11
  render() {
12
    return (
13
      <div className="wrapper" style={bgStyle}>
14
15
        <WrappedComponent {...this.props} />

16
      </div>

17
    );
18
  }
19
};
20
21
const SmallCardWithGreyBg = withGreyBg(SmallCard);
22
const BigCardWithGreyBg = withGreyBg(BigCard);
23
const HugeCardWithGreyBg = withGreyBg(HugeCard);
24
25
class CardsDemo extends Component {
26
    render() {
27
        <SmallCardWithGreyBg {...this.props} />

28
        <BigCardWithGreyBg {...this.props} />

29
        <HugeCardWithGreyBg {...this.props />
30
    }
31
}

The withGreyBg function takes a component as an input and returns a new component. Instead of directly composing the Card components and attaching a style tag to each individual components, we create a HOC that serves this purpose. The higher-order component wraps the original component and adds a <div> tag around it. It should be noted that you have to manually pass down the props here at two levels. We haven't done anything fancy, but this is what a normal HOC looks like. The image below demonstrates the withGreyBg() example in more detail.

Higher-Order Components example in ReactHigher-Order Components example in ReactHigher-Order Components example in React

Although this might not appear particularly useful right now, the benefits are not trivial. Consider this scenario. You are using React router, and you need to keep some routes protected—if the user isn't authenticated, all requests to these routes should be redirected to /login. Instead of duplicating the authentication code, we can use a HOC to effectively manage the protected routes. Curious to know how? We will be covering that and a lot more in the next tutorial.

Note: There a proposed feature in ECMAScript called decorators that makes it easy to use HOCs. However, it is still an experimental feature, so I've decided not to use it in this tutorial. If you're using create-react-app, you will need to eject first to use decorators. If you're running the latest version of Babel (Babel 7), all you need to do is install babel-preset-stage-0 and then add it to the plugin list in your webpack.config.dev.js as follows. 

1
// Process JS with Babel.

2
        {
3
            test: /\.(js|jsx|mjs)$/,
4
            include: paths.appSrc,
5
            loader: require.resolve('babel-loader'),
6
            options: {
7
              
8
              // This is a feature of `babel-loader` for webpack (not Babel itself).

9
              // It enables caching results in ./node_modules/.cache/babel-loader/

10
              // directory for faster rebuilds.

11
              cacheDirectory: true,
12
              presets: ['stage-0']
13
        },

Summary

In this tutorial, we learned the basic concepts of HOCs. HOCs are popular techniques for building reusable components. We started with a discussion of basic ES6 syntax so that it would be easier for you to get used to arrow functions and write modern-day JavaScript code.

We then had a look at higher-order functions and how they work. Finally, we touched on higher-order components and created a HOC from scratch. 

Next up, we will cover different HOC techniques with practical examples. Stay tuned until then. Share your thoughts in the comments section. 

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.