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.


    Show a Spinner While a Component is Loading using Recompose


    Learn how to use the 'branch' and 'renderComponent' higher-order components to show a spinner while a component loads.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    I have a withUserData higher-order component here. It fetches some user data, and it passes the data to any wrapped component. I'm using it here around my user component. It receives the user data in the form of name and status, and it's checking if name or status are undefined.

    It wants to show a spinner, otherwise show the user. If I refresh, I can see a spinner shows up for a couple seconds until the data is received. I would like to separate out the concern of the spinner. I'm going to store that into its own component.

    I'm also going to remove this logic here. Now, I'll declare a new higher-order component called withSpinnerWhileLoading. We'll make use of the branch higher-order component from Recompose. Branch is similar to an if-then statement.

    The first parameter is a predicate. If the predicate is true, it will render the second parameter. If it's false, it will render the third parameter. Our predicate is the WhileLoading part. We want to check if it's loading.

    If it is loading, I want to render a component, and I want to render the spinner component. The third parameter is actually optional. If you don't supply it, it will fall back to rendering the wrapped component. I often find that I don't supply a third parameter.

    Now, I have to define our isLoading predicate. The predicate in the branch higher-order component always takes in the component's props. Instead of checking for name or status, I'd like to be a little bit more deliberate.

    Let's go ahead and add a loading prop, and I'll just check for that. We'll return it. It'll either be true or false. Now, I need to add that.

    I'll add a getInitialState hook, and I'll make sure to return loading set to true initially. When I get my data, I want to set loading to false. Now, I want to compose both the withUserData and withSpinnerWhileLoading higher-order components into a single higher-order component.

    We'll use that one instead. I should be able to refresh and still see the same, exact behavior as before.