HOF and HOC (in React)

Image for post
Image for post

📄 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 function is a general concept that applies to many programming languages, including JavaScript.

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

An example of a function that takes another function as argument is this:

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

An example of a function that returns another function is this:

Tricky?

If you are not 100% confident about how higher-order functions work, I want to advise you to open up a JavaScript REPL and play around with it. I put the code in an online REPL here.

Examples

Also, Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are some of the Higher-Order functions built into the language.

Image for post
Image for post

Creating Our own Higher-Order Function

Let’s imagine JavaScript didn’t have the native `map` method. We could build it ourselves thus 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)

Ok, now we know what higher-order functions are. Higher-order components (HOC) are a very similar concept. Instead of working with functions as input parameters and return values, HOCs are working with components.

The most simple HOC

A HOC takes a component as input parameter and returns a new component. Let’s look at an example of the most simple HOC possible.

Image for post
Image for post

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:

Image for post
Image for post

Click here to see a fully working example.

Image for post
Image for post

Use HOC to enhance components

The HOC we just created does not do anything to the component, it just returns the same component with a wrapper component around it. It’s not much point with that, is it?

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:

Image for post
Image for post

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

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

Image for post
Image for post

…then we will enhance it with our HOC.

Image for post
Image for post

Click here to see a fully working example

Image for post
Image for post

Example no: 2

Observations

HOC is a powerful concept that is used to enhance a component with new functions or data. It is worth noting the following:

  • 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

source: https://css-tricks.com/what-are-higher-order-components-in-react/#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:

https://blog.jakoblind.no/simple-explanation-of-higher-order-components-hoc/#:~:text=The%20most%20simple%20HOC&text=This%20HOC%20takes%20a%20React,the%20WrappedComponent%20as%20a%20child

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