React Higher-Order Component.

Mohiuddin Mazumder
3 min readMay 2, 2021

What is HOC or Higher-Order Component?

A higher-order component is a function that takes a component as a parameter and returns a new component.

Why we need Higher-Order Component?

Before starting, we have to focus on React basic concept. React is a declarative, efficient, and flexible JavaScript library for building user interfaces. React always works with component-based. The component is one of the core building blocks of React.

And react has one of the most valuable features that is code reusability. Components reusable feature makes our life easier when we develop our frontend UI.

We can reduce code duplication using the component concept. As an example, In your application, the Home page always needs a navbar and a footer. And this navbar and footer also need another page. When you need to implement the same design or functionality in another component then just call the navbar or footer or any component. And just import the component at the top of your new component. That is the little basic concept of designing with react.

The same concept is working when we work for app functionality. Suppose, you have a value increment functionality in your application. Which you need in multiple components. That is actually code duplication because you are writing the same code in multiple components. In this situation, if we create a component that contains all common code and we can reuse the component. The same concept is working for the higher-order components. Higher-order components used to reduce code duplication.

The concept of higher-order components like spider-man! Peter Parker becomes Spiderman when wears his costume.

const spiderman = withCostume(peter parker);

How to use a Higher-order component?

We have two-component. The first component's functionality is value increment by clicking. And second one’s functionality is value increment for every hover.

The two-component have the same functionality. Having to write the same code in multiple places here. And now we can prevent code duplication with a higher-order component.

At first, all the same code written in a component.

That is the spiderman costume

After that, we just call the withCounter component and pass another component as a parameter of withCounter.

That is Higher-Order Component….

Conclusion:

All knowledge and info are shared as a learner. Please make corrections if anything is wrong.

Thank you.

--

--