HOF and HOC (in React)

📄 Table of Contents

The concept higher-order component comes from the functional programming concept higher-order function. Let’s start by looking into what higher-order functions are.

Higher-Order Functions (in JS)

Higher-order functions are regular functions that do one or both of the following:

  1. Takes one or many functions as arguments
  2. Returns a function

Let’s look at simple examples of these two.

1. Takes one or many functions as arguments

function addTwice(f, v) {
return f(f(v));
}

It takes a function called f, and calls it twice. This is an example usage:

function add(v) {
return v + 3;
}
const result = addTwice(add, 1);
console.log("Result is ", result);

That output would be:

<code class="">Result is 7

2. Returns a function

Tricky?

Examples

Creating Our own Higher-Order Function

Let’s say, we have an array of strings and we want to convert this array to an array of integers, where each element represent the length of the string in the original array.

In the above example, we created an Higher-order function mapForEach which accepts an array and a callback function fn. This function loops over the provided array and calls the callback function fn inside the newArray.push function call on each iteration.

The callback function fn receives the current element of array and returns the length of that element, which is stored inside the newArray. After the for loop has finished, the newArray is returned and assigned to the lenArray.

A much simpler solution that converts an array of strings into an array of the string’s lengths.

let names = ['John', 'Mac', 'Peter'];
let lengths = names.map(name => name.length);

console.log(lengths);

Higher-Order Component (in React)

The most simple HOC

Above HOC takes a React component, WrappedComponent, as parameter. It returns a new React component. The returned component contains the WrappedComponent as a child.

We use the HOC to create a new component like this:

Click here to see a fully working example.

Use HOC to enhance components

The idea with HOC is to enhance components with functions or data.

Let’s look at an example of an HOC that enhances the component.

The way we are going to do that is to add a prop to the component. Let’s add a name prop with the value “React”. It would look something like this:

Let’s take a look how we can use it.

First, we define the component to send in, which uses the name prop…

…then we will enhance it with our HOC.

Click here to see a fully working example

Example no: 2

Use Cases

Show a loader while a component waits for data

Observations

  • We don’t modify or mutate the component. We create new ones.
  • A HOC is used to compose components for code reuse.
  • A HOC is a pure function. That means it has no side effects. It only returns a new component.

A Higher-Order Component Example

Let’s start with a basic example. Here’s a higher-order component that transforms and returns usernames in uppercase:

const hoc = (WrappedComponent) => (props) => {
return (
<div>
<WrappedComponent {...props}>
{props.children.toUpperCase()}
</WrappedComponent>
</div>
)
}

This higher-order component receives a WrappedComponent as an argument. Then it returns new component with props passed to it creating a React element. We call .toUpperCase() on the props.children, to transform the passed props.children to uppercase.

To make use of this higher-order component, we need to create a component that receives props and renders the children.

const Username = (props) => (
<div>{props.children}</div>
)

Next, we wrap Username with the higher-order component. Let’s store that in a variable:

const UpperCaseUsername = hoc(Username)

In our App component, we can now make use of it like this:

const App = () => (
<div>
<UpperCaseUsername>Kingsley</UpperCaseUsername>
</div>
);

The UpperCaseUsername component is merely a rendering of the Username UI that, in turn, pulls in state from the WrappedComponent acting as the higher-order component.

HOC template

And use it that way in your component:

My Username component

References:

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

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