Higher order components: Simple explanation you may need to know

High order component, to clarify, are the advanced techniques in React for reusing component logic. HOCs are also not part of the React API, they are a pattern that emerges from React’s compositional nature. These functions are pure, which certainly means they are receiving data and returning values according to that data. So, if the data changes, higher order functions are re-run with different data input. All in all, everything we need to do is change the data that our function is using.

Whereas a component transforms props into UI, a high order component transforms a component into another component. HOCs are common in third-party React libraries, such as Redux’s connect and Relay’s createFragmentContainer. So, in this article, we would like to cover for you every simple explanation of high order component that you need to know. Consequently, by reading this article, you may understand better about this term. Let’s go!

#1. Functional programming and higher order functions

A higher order function is a function that accepts another function as an argument. You certainly would have already used the map function which falls under this category. This is a concept that is derived from the world of functional programming. But why use a functional programming concept to React?

As a result, the goal of the higher order components’ pattern is to decompose the logic into simpler and smaller functions that can be reused. A rule of thumb is a function that does just one task and does it well after all. This also avoids side effects (changing anything that is not owned by the function) and makes debugging and maintenance a whole lot easier.

#2. React higher order components

Higher order components in React
High order component in React

So, let’s look at some code straight away.

 const reverse = (PassedComponent) =>
  ({ childrenundefined ...props }) =>
    <PassedComponent {...props}>
      {children.split("").reverse().join("")}
    </PassedComponent>

const name = (props) => <span>{props.children}</span>
const reversedName = reverse(name)
<reversedName>Hello</reversedName>
//=> <span>olleH</span>

The above example takes a component and also reverses the content inside it. The reverse is a HOC, which takes in an element (name in the example), finds the content inside that element, reverses it, and also spits out an element with reversed content. What shown above is an extremely simple use case for the purpose of understanding the concept. Moreover, there are two things that happen with a HOC: Take the high order component as an argument and return something.

#3. The complex usage of high order component

So, we will refer to certain parts of the repo as we progress. This is a react app made by using create-react-app. Firstly, let’s understand how the app works. To clarify, let’s assume that we are building a feed of random users. After that, in App.js we make a request to randomuser.me to get some random data. The request will be made inside the componentDidMount function as a result.

 componentDidMount() {
    fetch("https://api.randomuser.me/?results=50")
      .then(response => response.json())
      .then(parsedResponse =>
        parsedResponse.results.map(user => ({
          name: `${user.name.first} ${user.name.last}`undefined
          email: user.emailundefined
          thumbnail: user.picture.thumbnail
        }))
      )
      .then(contacts => this.setState({ contacts }));
  }

The random data from the API is processed since we are only interested in the name, email and the image, we filter it out and set it as the app state. Once we have the data for our high order component, we pass the contacts to our Feed object as:

<Feed contacts={this.state.contacts} />

Here is how our Feed component looks. To clarify, it simply passes the received contact data into FeedItem. And also, FeedItem iterates through the data to actually display it.

 import Reactundefined { Component } from "react";
 import FeedItem from "./FeedItem";
 import Loading from "./HOC/Loading";

 import FeedStyle from "./Feed.css";

 class Feed extends Component {
   render() {
     return (
       <div className="justify-content-center align-items-center">
         <FeedItem contacts={this.props.contacts} />
       </div>
     );
   }
 }

 export default Loading("contacts")(Feed);

You would have noticed that the export statement is different from the normal case. Instead of Feed, we export the Feed component wrapped in a Loading component. This is because our Loading HOC is a curried function. Currying, to clarify, is the process of breaking down a function into a series of functions that each take a single argument.

The loading component – one of the most important of high order component

For instance, let’s take a look at our Loading component.

 import Reactundefined { Component } from "react";

 const isEmpty = prop =>
   prop === null ||
   prop === undefined ||
   (prop.hasOwnProperty("length") && prop.length === 0) ||
   (prop.constructor === Object && Object.keys(prop).length === 0);

 const Loading = loadingProp => WrappedComponent => {
   return class LoadingHOC extends Component {
     componentDidMount() {
       this.startTimer = Date.now();
     }
 
     componentWillUpdate(nextProps) {
       if (!isEmpty(nextProps[loadingProp])) {
         this.endTimer = Date.now();
       }
     }
 
     render() {
       const myProps = {
         loadingTime: ((this.endTimer - this.startTimer) / 1000).toFixed(2)
       };
 
       return isEmpty(this.props[loadingProp]) ? (
         <div className="loader" />
       ) : (
         <WrappedComponent {...this.props} {...myProps} />
       );
     }
   };
 };
 
 export default Loading;

Let’s understand how the loading high order component work step by step.

  • For ease of understanding assume component, takes another component ( in our case Feed component) along with a property contact.
  • After that, the Loading component checks of the loadingProp (in our case contacts) are empty – The function is Empty does this.
  • If it’s empty the Loading component returns <div className=”loader” />, then we use the classname loader to add some styles and implement the loader.

Final words

That may conclude some of the most simple explanations of high order component that you may need to know for your website. All in all, high order component can be used for different functionalities. These pure functions are certainly the essence of functional programming. Once you are used to it, you will notice how your app is becoming easier to maintain or to upgrade.

Until now, are you clear all about the above information? In case, you are still confused. So don’t hesitate. Let ArrowHiTech know by filling this CONTACT FORM. More importantly, please remember that ArrowHiTech is one of the leading IT Company in VietNam. We also provides the best Web Application Development Services as well as Mobile Application Development Services. Thus, don’t miss the awesome services of ArrowHiTech. Let’s check it out right now.

ArrowHiTech is always ready to support your business succeed!


Tags

Share