Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Write a Higher Order Component from Scratch

    Tim KindbergTim Kindberg

    Learn the proper patterns for writing a higher order component from scratch.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    A higher order component typically always has the same structure. It takes in a base component and it returns a component, in this case, it's a functional stateless component. Then it renders out the base component and it spreads the props in.

    Now, if we create another user and we pass our first user to our higher order component, it's not going to modify it in any way, but we will have a valid React component. I just have to add the name. You see, the prop signatures identical to user, and it renders exactly the same.

    Now if we want our higher order component to actually do something, typically you add a configuration step. Here we'll take in some props we'd like to override and then we can spread those onto the component as well. Now, we have to use our configuration phase and pass in any prop that we'd like to override.

    Now the name will always be Bob, regardless of what I change the name in the JSX. You could save the configuration portion of the higher order component call into a variable. We can call this one Always Bob, sometimes that's nice for readability. Then we can name our higher order component properly, as well.

    Another reason you might want to create a higher order component is to tap into a lifecycle hook. In this case, I need to use a class component and we have to do the same thing where we return the base component and spread the props in. Perhaps we want to create a component that never updates.

    We could tap into the shouldComponentUpdate() method, and we can return false. We don't need a configuration step for this phase. We can call this Never Render. Now, User 2 will never render. We also don't need this portion of the functional stateless component, and we also need to change this to this.props because we're using a class component.

    Now, if Steve were bound to some data and it changed the update would not be reflected.