Higher order components (Hoc) in React with examples

Higher order components (Hoc) in React with examples

In this tutorial, we are going to learn about what are higher-order components and how to create it.

What are Higher order components (Hoc)?

The Higher order component is a JavaScript function which takes the other component as an a argument and returns new component.

Higher order components help us to reuse the component logic.

There are already some other react libraries using hoc pattern like connect in redux and withRouter in a react-router library.

Creating Higher order component

We are creating a higher order component which helps us to log the component props.

hoc.js
import React from "react";

function LogProps(MyComponent) {

  class NewComponent extends React.Component {

    componentDidMount() {
      console.log(this.props);    }

    render() {
      return <MyComponent {...this.props} />;    }
  }

  return NewComponent;}

export default LogProps;

In the above code, we created a function called LogProps which accepts other component as an argument and returning Newcomponent with logging props.

Using Higher order component

Welcome.js
import React from "react";
import LogProps from "./hoc";
function Welcome(props) {
  return <h1>Welcome {props.name}</h1>;
}

export default LogProps(Welcome);

Here we imported LogProps component and passed Welcome component as an argument so that we can see Welcome component props inside the browser’s console.

import React from "react";
import Welcome from "./Welcome";

function App() {
  return (
    <div className="App">
      <h1>Hello React</h1>
      <Welcome name="gowtham" />
    </div>
  );
}

hoc-example

Have you seen in the above image Welcome component props object is logged inside the console.

This a simple example, you can also create higher order components to protect your private routes in a similar way.