DEV Community is a community of 787,776 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. Make React Higher Order Component HOC an easy one

Before starting to learn Higher Order Component, we need to clear our concept about Higher order Function.

Higher Order Function in JavaScript
A Higher Order Function is a function which -

1. Takes a function as argument
2. Returns another function

Ok, Let's see an example of a Higher Order function in JavaScript.

function sum(a, b) {
return a + b;
}

function multiplication(a, b) {
return a * b;
}

// result() is a Higher Order Function
function result(operation) { // operation is actually an another function
return function(a, b) { // return function
return "Result of operation: " + operation(a, b);
}
}

const sumResult = result(sum);
const multipleicationResult = result(multiplication);

console.log(sumResult(1, 200)); // Result of operation: 201
console.log(multipleicationResult(2, 200)); // Result of operation: 400

In the above example, result() is a higher order function which accepts the arithmetic operation as it's parameter.
Then, it returns a function and manipulates it in a way and return the function data.
So, by this approach - We don't have to duplicate

Result of operation:

text. We can re-use our entire sum(), multiplication() functions.

Now, let's talk about Higher Order Component -
Higher Order component is a pure JavaScript function, which -

1. Takes a Component as parameter
2. Returns another Component

Example:
Suppose we have 2 pages called - About Page and Home Page, the component could be like this -

HomePage component

import React from "react";

const HomePage = () => {
return (
<div>

</div>

<footer>
Some Footer Content
</footer>

</div>
);
};

export default HomePage;

import React from "react";

const AboutPage = () => {
return (
<div>

</div>

<footer>
Some Footer Content
</footer>

</div>
);
};

But, look here, we've copied the same Header and Footer part for both of these component. So now, we could re-use this logic using a Higher Order Component very easily.

hocs/Layout.js

import React from "react";

const withLayout = (PageComponent) => {
return function WithPage({ ...props }) {
return (
<div>

<!-- Called The Component Parameter -->
<PageComponent />

<footer>
Some Footer Content
</footer>

</div>
);
};
};

export default withLayout;

That's great, now we could use our HomePage and AboutPage component very easily.

import React from "react";
import withLayout from "./hocs/Layout";

const HomePage = () => {
return (
<h2>HomePage</h2>
</div>
);
};

export default withLayout(HomePage);
import React from "react";
import withLayout from "./hocs/Layout";

const AboutPage = () => {
return (