Explaining Higher-Order Component (HOC)

Hasan Ugur
Segmentify Tech Blog
2 min readJun 22, 2022

We can say that Higher-Order Component (HOC) is an upper layer component, basically a function that takes a component as a parameter and returns a new component as output.

However, before discussing HOC, we will briefly talk about the Higher-Order Function structure, which is the source of this structure.

What is Higher-Order Function?

We call the functions that take a function as a parameter or give a function as an output Higher-Order Function. Such functions do not have to meet both conditions at the same time. In fact, some array functions that we use frequently are examples of this structure. .map(), .filter(), .reduce(), .forEach() are some of the examples.

For example, let’s explain this structure by focusing on the filter function:

First, let’s write a normal function that finds even numbers in the array we have.

This function is designed to return even numbers to us and cannot be used for any other purpose. However, if we use the same operation with “filter”, which is a Higher-Order Function, we can easily find odd numbers besides even numbers by defining a function inside:

What is Higher-Order Component?

Facebook calls this structure a “more advanced way to use React components”. In short, we can define Higher-Order Component as a function that takes a component, expands the properties of the component, and outputs a new component.

With this method, you can add a common feature to your components; it is entirely up to you. For example, you can log from each component you add using HOC, add a common layout or pass a common data into the component.

Now let’s make the HOC structure easier to understand with a simple example. Every component used with this HOC structure should be logged in the “Did Mount” and “Unmount” stages.

Let’s define the HOC first:

Now let’s add this HOC to an example component as static so that this component will be logged wherever it is used.

Another way of using it is that instead of adding the HOC to the component as static, we can add it while calling the component. In this case, you can use the HOC structure wherever you want.

We have written a HOC that logs on every component used in this way. I hope it was clear to anyone who reads it. To use a more advanced HOC, you only need to use your imagination and apply it to the HOC structure.

Thanks for reading to the end :)

--

--