You are currently viewing What are Higher-Order Components in ReactJS?

What are Higher-Order Components in ReactJS?

Higher-Order Components in ReactJS

In this article, we will see what is Higher Order Components in ReactJS. There are three types of components in ReactJS they are :

  • Class component
  • Functional component
  • Higher order component

What are Higher Order Components?

A Higher Order Component will be refer to as HOC. It is a pattern where a function takes a component as an argument and returns a new component. In simple code it will look something like this:

const NewComponent = higherOrderComponent(originalComponent)

In the above code, we have created a constant called “NewComponent” and assigned it to the function called “higherOrderComponent()” and we pass in the “originalComponent” as an argument. Typically HOC adds additional data or functionality to the originalComponent. So, the new component can also be referred to as an enhanced component like this:

const EnhancedComponent = higherOrderComponent(originalComponent)

Example of HOC in ReactJS

If you were to understand this from a non-technical point of view, you have IronMan is equal to without passing in Tonystark as a parameter.

const IronMan = withSuit(Tonystark)

Here TonyStark is the originalComponent with a suit being the function that will enhance TonyStark and return IronMan which is the enhancedComponent.

From React point of view, we have a function that accepts the originalComponent adds functionality, and returns enhanced component, or in other words, we have the HOC pattern.

Leave a Reply