Introduction

If you are working on React web applications, sometimes you have copies of the same logic in multiple components. Instead of writing the same logic/code in multiple places, can we have logic in the single component and share it across the application? Yes, there is a solution for sharing the common logic/component across the multiple components in the application. It is called Higher-Order Components. In this article, we are going to explore Higher-Order components and their use.

Higher-Order Components

The examples of HOCs are Redux's connect.

JavaScript
import React from 'react'

export default function HOCFunction(OriginalComponent) {
  class HOCClass extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: "Data from HOC Component"
      };
    }

    componentDidMount() {
      this.setState({
        data: "Data from HOC"
      });
    }

    render() {
      return (
        <div style={{ backgroundColor: "#74f795", padding: "10px" }}>
          <h1 style={{ color: "red" }}>This is HOC Class</h1>
          <OriginalComponent {...this.props} data={this.state.data} />
          <br />
        </div>
      );
    }
  }
  return HOCClass
}

The above code snippet is a simple example of the HOC. In the above code,

We can consume the "HOCFunction" as follows,

JavaScript
import React from 'react';
import HOCFunction from "./HOC";

class MyComponent extends React.Component {
  render() {
    return (
      <div style={{ backgroundColor: "#c9d1ce", padding: "10px" }}>
        <h1>This is Original Component</h1>
        <h3 style={{ color: "red" }}>{this.props.data}</h3>
      </div>
    )
  }
}

MyComponent = HOCFunction(MyComponent);
export default MyComponent;

Example

Consider the scenario, there are two different components, and both having common search functionality. How to implement it using HOC?

I have created a simple application that has search functionality using HOC. In this application,

"HOC.js" have HOC called "SearchHOCFunction" and inputs of the HOC is component and data and it returns the "HOCClass" component.

JavaScript
render() {
  return (
	<div style={{ backgroundColor: "#74f795", padding: "10px" }}>
	  Search : <input type="text" onChange={this.changeValue}></input>
	  <br/>
	  <br/>
	  <OriginalComponent {...this.props} searchData={this.state.searchData} />
	  <br />
	</div>
  );
}

Inside the "HOCClass", implemented the search functionality.

JavaScript
data.forEach(item => {
	if (item.toUpperCase().includes(e.target.value.toUpperCase())) {
	  searchItem.push(item);
	}
});

Created the two components which are "Product" and "Brand". These two components are wrapped with the "SearchHOCFunction".

JavaScript
Product = SearchHOCFunction(Product, ProductData);
export default Product;

//Here ProductData is,
var ProductData = [
  "TV",
  "Mobile",
  "Laptop",
  "Headphone",
  "Desktop"
]
JavaScript
Brand = SearchHOCFunction(Brand, BrandData);
export default Brand;

//Here BrandData is,
var BrandData = [
  "Samsung",
  "LG ",
  "OnePlus",
  "Apple",
  "Microsoft"
]

If you are typing the text in the search box (Higher-Order component), it will perform the search and return the search result data to the respective component, and then search result data will be displayed in the component.

So, here instead of writing search functionality in the two components, created on HOC for search functionality and wrapped around the necessary components.

Summary

A Higher-Order component is a function that takes a component and returns a new component. The main use of HOC is to improve the reusability of particular component/logic across the application. I hope you have liked it and know about Higher-Order components and how to implement them in React applications.