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.


    Preload React Components with the useEffect Hook

    Kent C. DoddsKent C. Dodds

    While users are filling out the form on our home page, it would be a good idea to pre-load the next page they will be going to so they don't have to wait for it to load once they've finished filling out the form. React's useEffect hook makes this really easy.



    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




    Instructor: We're treating our users right by using react.lazy to dynamically import the JavaScript that the user is going to need eventually, depending on the area of the app that they're going to go to. We only load the home and only load the user when those are actually going to be rendered.

    This can lead to a bit of a problem for users on slow connections. If we go in here, and we'll switch us down to a slow 3G, and then I say Kent C. Dodds, for example, then we'll go. We're going to load the application, and it's going to sit there for a little while before we start loading the data.

    It'd be really nice if we could preload the user page when we're on the homepage, because we can assume with pretty good confidence that a user that's on the homepage is going to go to the user page next.

    One trick that we can do is if we go into our screen's home, index.js here, we can import useEffect from react. Then I'll take that useEffect in my home, and I'll have an effect that runs only one time, when the component mounts.

    When this component mounts, we'll preload the next page. How are we going to do that? With the way that webpack works, we could actually just do an import for that user page. webpack will start loading that as soon as this homepage has been loaded.

    Let's take a look at what this does now. If I pop open my developer tools, and I refresh here, I'm going to see that I'm loading my bundle, my chunks, and then once this page is loaded, we're actually going to follow up with a request for our other chunks that we need for the user page.

    If I go down to a slow connection again, we clear this out, and I click go, we're actually immediately going to be making that request for the GraphQL data, rather than having to make a request for the rest of the application, which works perfectly for our use case.

    We know that users who are going to the homepage are going to go to the users page next. It makes a lot of sense to preload the JavaScript for the next page while the user is filling out this form.