i2tutorials

What is HOC component in react

                               

A higher-order component (HOC)is a function that takes a components and returns a new component. React’s Higher Order Component is a pattern that originates from React’s nature that privileges composition over inheritance. A higher-order component (HOC) is an new technique in React for reusing components logic in multiple components.

The HOC(higher-order component ) function accepts another functions as an argument. The map function is the best example for understanding this. The main goal of hoc is to divide the component logic into simpler and smaller functions that can be resued as we need.

A higher-order component(HOC) transforms a components into another components. Note that a HOC does not modify the input component. Rather, a HOC(higher-order component) composes the original components by wrapping it in a container components.

A HOC( higher-order component) is a pure function with zero side-effects.

Example : 

Create a new file with the name HOC.js. In this file, we have made one function HOC( higher-order component) . It accepts one argument as a components. Here, that components is App.

File Path : src/HOC.jsx

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

Now, include HOC.js file into the App.js file. In this file, we need to call the HOC( higher-order component) functions. The App components wrapped inside another React components so that we can modify it. Thus, it becomes the primary application of the Higher-Order Components.

File path : src/App.js

import React, { Component } from "react";
import Hoc from "./HOC";
class App extends Component {
  render() {
    return (
      <div>
        <h2>HOC Example</h2>
        This is a Higher Order Component
      </div>
    );
  }
}
App = Hoc(App);
export default App;

Output: 

a1

Higher-Order Component Conventions

 

Exit mobile version