Comments

React Higher Order Components For The Newbie

So you have been coding in React now, and liking it! Great! Did you know about this interesting pattern that you can use in React called, High Order Components? In this post, let’s take a quick look at what Higher Order Components are, and how you can use them in your app?

Yes I know you are like this kid, going “One more new thing to learn?!?!”. Yup trust me it is not hard, and it may come in handy while you code your React App! ūüôā And this is completely optional, you can still build awesome React apps, without Higher Order Components. But it is a common design pattern that you will appreciate and use once you learn what it is.

Background: High Order Functions

The concept of a high order component is not a new one that came with React. In JavaScript we use what is called a High Order Function at times.

A function that accepts and/or returns another function is called a higher-order function.

The diagram below represents a high order function conceptually.

higher-order function

I have written an article on this a while ago, which you can read to get a better understanding of high order functions.

What are high order functions in JavaScript?

What are React Higher Order Components

Now we can extend the same concept into the component architecture in React. In React everything is a component.

A Higher Order Component (HOC) is a function that takes a component and returns a component.

Note: HOCs are not really a part of the React API, but this is more of a code pattern that seems to be a good fit with React because of its compositional nature.

The Problem HOCs Solve

Before we get into writing Higher Order Components, it is fair to ask, “What is the problem that HOCs are trying to solve?”

In software development one of the commonly talked about principle is “Don’t Repeat YourSelf” aka. DRY. I have used the DRY principle across multiple languages during my career, and have been advised to do so by experts in the industry. Creating a simple utility function, that is used across several parts of the codebase is something you may have done frequently. You are essentially following DRY by doing so. You are reusing the same utility function, without repeating the code.

In React, one of the ways to achieve DRY across components, is to use the Higher Order Component (HOC) concept. You can share common functionality without repeating code using HOCs.

Structure of HOC

Here is what a HOC looks like in React. The Higher Order Component is essentially a function, that takes in a component as an argument, and returns a new component. It can also render the original component that was passed to it as an argument.

function myHOC (myOtherComponent) {
  return class extends React.Component {
    render() {
      return <myOtherComponent {...this.props}/>
    }
  }
}

In the simple example we see above the myHOC is a function that takes in myOtherComponent as a parameter. It then returns a new component. The new component contains myOtherComponent as a child in this case.

I Learn by Example!

At this point, you may get an idea of what Higher Order Components are in React and why they are used. To recap:

  • HOC function that takes in a component and returns a new component.
  • It is primarily use to reuse code and follow the DRY principle in React.
  • It is not an API and is a design pattern that fits well within React.

Alright, let’s look at a simple example to understand how HOCs can be put into action.

Create Component

class BlogInformation extends React.Component {
  render() {
    return (
      <div className="blogInfo">
        <h3>Blog Author: {this.props.author}</h3>
        <h3>Article: {this.props.article}</h3>
      </div>
    );
  }
}

I have created a component BlogInformation and this component is a simple class component that displays the name of the author passed to it, and the name of the article written by an author. Both the name and the article are passed to the component as props. Simple enough!

Call Component

I am going to call this component from the App.js file and pass the props to it.

export default function App() {
  return (
    <div className="App">
      <BlogInformation author="Adhithi" article="New article" />
    </div>
  );
}

So far, we have done nothing special. We just created a component and called that component from the parent component. When we run this code, this what we will see.

Alright, now let’s start to think about enhancing this component. What if I want it to display the author name and “No articles written” in the article section, when no article is passed as prop? If there were no author passed to the component, I want it to display a custom message as well. At this point, the component starts to grow. Keep in mind we are still dealing with a simple feature that we can have all of this in one component, without the use of a HOC. But this post is aiming to illustrate the use of HOC with a simple example to understand how to use it.

Alright, I am going to tweak our BlogInformation component a little bit.

class BlogInformation extends React.Component {
  render() {
    return (
      <div className="blogInfo">
        <h3>Blog Author: {this.props.author}</h3>
        <h3>Article:{" "}
          {this.props.article ? this.props.article : "No articles written"}
       </h3>
      </div>
    );
  }
}

We are going to display “No articles written” if the¬†article¬†was not passed in the¬†props.

Create Higher Order Component

Now is a good chance to create a HOC for the rest of the changes.

const myHOCFunction = MyComponent => {
  return class extends MyComponent {
    render() {
      if (this.props.author) {
        return <MyComponent {...this.props} />;
      } else {
        return (
          <div className="UserInfo">
            <h3>There are no authors at this time</h3>
          </div>
        );
      }
    }
  };
};

export default myHOCFunction(BlogInformation);

Here is a summary of the code above:

  • We have created a HOC¬†myHOCFunction,¬†that takes in a component and returns a new component.
  • This function checks if the¬†author has been passed in the¬†props¬†to the component.
  • If the¬†author¬†exists, then it renders the component that was passed with no changes.
  • When the¬†author¬†information is unavailable, it renders a new component with a custom message.
  • Towards the end, we are invoking the HOC by passing in the¬†BlogInformation¬†component as a parameter.

Now, anytime the BlogInformation component is called, it will go the HOC myHOCFunction and render instead. You may now get the idea on why HOC can be useful to you on large React projects. You maybe able to create HOCs to reuse a ton of code, that would have otherwise been repetitive.

To see this working, you can go to the code sandbox below:

React HOC Sandbox

Conclusion

Higher Order Components lets your abstract your code, and once you get a hang of it, you may be using this pattern too often. Again, HOC is just a design pattern, and you can opt to use it or not depending on your coding style and preferences.

If you want to play with the code samples I used in this blog post, they are available on my GitHub Repo below:

React HOC Examples

Resources:

React HOC Documentation

Mosh’s Mastering React Course (Updated with Hooks)

I hope you enjoyed this post. Please share it and you can follow me on twitter for more at @AdhithiRavi

Adhithi Ravichandran is a Software Consultant based in Kansas City. She is currently working on building apps with React, React Native and GraphQL. She is a Conference Speaker, Pluralsight Author, Blogger and Software Consultant. She is passionate about teaching and thrives to contribute to the tech community with her courses, blog posts and speaking engagements.
Tags: , , , , , , ,

4 responses to “React Higher Order Components For The Newbie”

  1. Muhammad Irfan says:

    Hi Mosh, Can you please tell me which software you use for creating animating videos for courses?

  2. danny says:

    Hi Adhithi, thanks for your article! I’m still new to React, so HOCs are new to me as well. So why not just conditionally render the something like this:
    “`
    class BlogInformation extends React.Component {
    render() {
    return (

    Blog Author: {this.props.author}
    Article:{” “}
    {this.props.article
    ? this.props.article
    :
    There are no authors at this time

    }

    );
    }
    }
    “`

    instead of using the HOC? I don’t see the advantage, it just seems like more code to me.
    Thanks, Danny

    • Chan says:

      myHOCFunction is intended to Wrap “other Component” aside from “BlogInformation”. So that you will not need to repeat the “else” condition to “other Component”. you just wrap it with myHOCFunction.
      Make sense now?

  3. Danny says:

    Oops, can’t edit the message. Rendering this in the ternary operator
    <div className="UserInfo"
    <h3There are no authors at this time</h3
    </div

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts

    %d bloggers like this: