Higher-Order Components (HOC)

Abhay Jain
1 min readJan 12, 2021

--

Higher-order function is a general concept that applies to many programming languages, including JavaScript.

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.

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

1. Takes one or many functions as arguments

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

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

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

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

That output would be:

Result is 7

2. Returns a function

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

function addX(x) {
return function (y) {
return x + y;
}
}

And we would use it like this:

const add1 = addX(1);add1(5); // will return 6

We could also call the returned function directly without assigning it to a variable:

addX(1)(5); // will return 6

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.

--

--

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.