React Higher-Order Components

React Higher-Order Components

In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new component. It is not the feature of the React API, but a pattern which emerges from React compositional nature. These are similar to the functions of JavaScript that are used to add the additional functionalities in the existing component.

The HOC function accepts the other function in the form of an argument. The main goal of it to decompose the component logic into smaller and simpler functions, which can be reused in the future.

Syntax:

const NewComponent = higherOrderComponent(WrappedComponent);

As we know that, the component transforms the props into UI, and the HOC converts the component into another component and also allows us to add the additional data or functionality into it. Higher-order components are common in the third-party libraries. Some of the examples of the HOCs are Redux’s connect and Relay’s createFragmentContainer.

Let’s understand the working of HOCs by using the following example:

//Function Creation  
 function mul (x, y) {  
   return x * y  
 }  
 function higherOrder(x, addReference) {  
   return addReference(x, 20)  
 }  
 //Function call  
 higherOrder(30, mul) // 600   

In this example, there are two functions mul() and higherOrder(). Now, we are also giving the mul() function as an argument to the higherOrder() function.

The function gets passed, is called a callback function, and the function where you have passed the callback function is called as higher-order (HOCs) function.

Example:

Now, create a new file HOC.js, and make another function HOC in it. It will accept one argument as a component.

HOC.js

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

Include the HOC.js file into your App.js file. In this file, we have to call the HOC function.  

App = Hoc(App); 

App.js

import React, { Component } from 'react'; 
import Hoc from './HOC'; 
class App extends Component { 
render() { 
return ( 

Example of Higher Order Components

Hello World :) :)

Welcome to the tutorialandexample.com

) } } App = Hoc(App); export default App;

Output:

After the execution of the above code, the output will be:

call the HOC function.

Higher-Order Component Conventions

  • It is not recommended to use the HOCs within the render method of the component.
  • The static methods must have copied over for their accessing. It can be done by using a hoist-non-react-statics package for automatically copying all the non-react static methods.
  • If you want to add the ref to the element within the HOC component, then the ref refers to the instance of the outermost container component, instead of the wrapper component.



ADVERTISEMENT
ADVERTISEMENT