/    /  ReactJS- React Higher-Order Components

React Higher-Order Components

 

In React, HOC(higher-order component) is an advanced technique for reusing react UI component logic. It is a react component function that takes a react UI component and returns a new react UI component. According to the official website, it is not the feature in React API, but a pattern that emerges from React compositional nature. They are similar to JavaScript functions used for adding additional functionalities to the existing react UI component.

A react HOC (higher-order component function) accepts another function as an argument. The react map function is the best example to understand this HOC. The main goal of this is to decompose the react component logic into simpler and smaller functions that can be reused as you need.

Syntax:

const NewComponent = higherOrderComponent(WrappedComponent);

Example:

//Function Creation
function add (a, b) {
  return a + b
}
function higherOrder(a, addReference) {
  return addReference(a, 30)
}
//Function call
higherOrder(30, add) // 60

In the above example, we have created two react functions add() and higherOrder(). Now, we provide the add() function as an argument to the higherOrder() function. For invoking, rename it and reference in the higherOrder() function, and then invoke it.

 

Here, the react function you are passing is called a callback function, and the react function, where you are passing the callback function, is called a higher-order(HOCs) function.

Example :

HOC.js:

import React, {Component} from 'react';

export default function Hoc(HocComponent){
  return class extends Component{
   render(){
     return (
        <div>
          <HocComponent></HocComponent>
        </div>

      );
    }
  }
}

 

Include HOC.js file into the App.js file:

App=Hoc(App);

App.js

import React, { Component } from 'react';
import Hoc from './HOC';

class App extends Component {
 render() {
  return (
   <div>
    <h2>HOC Example</h2>
    I2tutorials provides best CS tutorials.
   </div>
  )
 }
}
App = Hoc(App);
export default App;