React.js Higher Order Components

Reactjs Higher-Order Components also known as hoc is a function that takes a component and produces a new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

It wraps around a normal component and gives additional data input. It is a technique to reuse component logic. HOCs are not part of React API. They are patterns that arise from React’s compositional nature. Components transform props into UI and HOC converts components to another component. Let’s analyze through an example. 

import React from 'react';


var newData = {

   data: 'Data from HOC...',

}


var MyHOC = ComposedComponent => class extends React.Component {

   componentDidMount() {

      this.setState({

         data: newData.data

      });

   }

   render() {

      return <ComposedComponent {...this.props} {...this.state} />;

   }

};

class MyComponent extends React.Component {

   render() {

      return (

         <div>

            <h1>{this.props.data}</h1>

         </div>

      )

   }

}


export default MyHOC(MyComponent);

In our example MyHOC is an HOC function that we use to pass data to MyComponent. The function takes the component and returns it along with newData. When we run the app it will display the following result. Data from HOC