Higher-Order Components (HOC)

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));
}
function add3(v) {
return v + 3;
}
const result = twice(add3, 1);console.log("Result is ", result);
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;
}
}
const add1 = addX(1);add1(5); // will return 6
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.

--

--

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
Abhay Jain

Abhay Jain

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