Advertisement
  1. Code
  2. React
Code

A Gentle Introduction to Higher-Order Components in React

by
Difficulty:BeginnerLength:MediumLanguages:
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

Function With a Single Parameter

Function With Multiple Parameters

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:

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

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

Spread Syntax in Array Literals

Spread Syntax in Object Literals

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

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. 

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:

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. 

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

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.

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 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. 

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
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.