techStackGuru

React High Order Components


High-Order Components (HOCs) are patterns for composing components in React. A component is passed to this function, and a new enhanced component is returned. A HOC allows you to reuse component logic, add new functionality, and modify behavior without changing the underlying component.

Example

import React from "react";

// Higher-Order Component (HOC)
const HOC = (WrappedComponent) => {
  return class extends React.Component {

    componentDidMount() {
      console.log("Component was mounted.");
    }

    componentWillUnmount() {
      console.log("Component was unmounted.");
    }

    render() {
      return <WrappedComponent />;
    }
  };
};

// Regular component
class MyComponent extends React.Component {
  render() {
    return <div>My Component</div>;
  }
}

// Enhanced component using HOC
const EnhancedComponent = HOC(MyComponent);

// Usage of enhanced component
const App = () => {
  return <EnhancedComponent />;
};

export default App; 

// Output Console
Component was mounted.
Component was unmounted.

// Output Display UI
My Component 

Our example above uses a Higher-Order Component called HOC to enhance components that are passed as arguments. As the component is mounted and unmounted, a message is sent to the console.

Using the regular component MyComponent, a div with the text "My Component" will be rendered. By passing MyComponent as an argument to the HOC, we can enhance MyComponent with logging capabilities. As a result, the EnhancedComponent has the logging behavior added.

Lastly, we render the EnhancedComponent in the App component. During mounting and unmounting this component, you will see logging messages in the console.

Lets see another example

import React from 'react';

// Higher-Order Component (HOC)
const withAuthentication = (WrappedComponent) => {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        isAuthenticated: false,
      };
    }

componentDidMount() {
    // Simulating authentication logic
    setTimeout(() => {
    this.setState({ isAuthenticated: true });
    }, 2000);
}

render() {
    const { isAuthenticated } = this.state;

    if (!isAuthenticated) {
    return <div>Loading...</div>;
    }

    return <WrappedComponent {...this.props} />;
}
};
};

// Regular component
const HomePage = () => {
  return <div>Welcome to the homepage!</div>;
};

// Enhanced component using HOC
const AuthenticatedHomePage = withAuthentication(HomePage);

// Usage of enhanced component
const App = () => {
  return <AuthenticatedHomePage />;
};

export default App; 

Here, the higher-order component called withAuthentication returns a component enhanced by the authentication information. A logic for authentication has been added to the enhanced component.

Usually, the HomePage component renders a div with a welcome message.

In order to enhance HomePage with authentication, we pass HomePage as an argument to the withAuthentication HOC. As a result, the AuthenticatedHomePage is created, which waits for a simulated authentication process to occur. As soon as the authentication has been completed (after 2 seconds), the AuthenticatedHomePage renders the HomePage component. As part of the authentication process, a loading message is displayed.

Our final step is to render the AuthenticatedHomePage in the App component.

The HomePage component will be rendered after 2 seconds when you run this example. In this example, we can see how a HOC can be used to add authentication functionality to a component.