Preload React Components with the useEffect Hook

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet

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.

Instructor: [00:01] 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.

[00:17] 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.

[00:34] 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.

[00:45] 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.

[01:05] 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.

[01:22] 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.

[01:39] 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.

[01:55] 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.

~ 2 years ago

How can this be used in large scale application with more than one route in a clean way?