Higher Order Components in ReactJS

React Higher-Order Components
Also known as HOC, the React Higher-Order Components is an advanced technique that takes a component and returns a new component. It is used for reusing component logic.

 

Higher-Order Component Conventions:

  • HOCs should not be used inside the render method of a component.
  • To have access to the higher-order components, the static methods must be copied over.
  • Since ‘Refs’ does not pass through as a parameter or argument, hence HOCs does not work for refs.
  • If a ref is added to an element in the HOC component, it will not be referred to as a wrapped component but will be referred to as an instance of the outermost container component.

Syntax:

const NewComponent = higherOrderComponent(WrappedComponent);

Example 1:

function sub (x, y) {  
  return x - y  
}  
function higherOrderComp(x, subReference) {  
  return subReference(x, 10)  
}  
higherOrderComp(50, sub)

Explanation:
Here, we have created a function sub() and pass it as an argument to the higherOrderComp() function. For invoking, we renamed it as subReference in the higherOrderComp() function. Thus, a callback function is passed to a higher-order(HOCs) function.

Example 2:
HOC.js:

import React, {Component} from 'react';  
export default function Hoc(HocComponent){  
return class extends Component{  
render(){  
return (  
<div>  
<HocComponent></HocComponent>  
</div>  
);  
}  
}   
}

App.js:

import React, { Component } from 'react';  
import Hoc from './HOC';  
class App extends Component {  
render() {  
return (  
<div>  
<h2>Hello World!!</h2>  
<p> Have a Great day.</p>  
</div>  
)  
}  
}  
App = Hoc(App);  
export default App;

Output:

Explanation:
A file named HOC.js is created. It includes a function HOC, which accepts one argument as a component and that component is App in this example. The HOC.js file is then into the App.js file, and then later called. The App component is wrapped inside another React component. Thus, it is the primary application of the Higher-Order Components and we can modify it.

Please Share