When you load an application, you don't want to load every component to the browser all at once. This can take forever to load, especially over a slow network.
With React.lazy
, you can now code split your components and only load them when they are needed. Once a component is loaded, it will stay loaded within the application.
In this lesson, you will:
Suspense
Suspense
that will render while the lazy loaded component is loadingInstructor: [00:00] Here we have a check-box that we can use to show and hide this cool Vanilla Tilt effect that we have here. But when we load the page, if we refresh here, we're going to see we're loading a bunch of JavaScript.
[00:10] We're loading the JavaScript that's necessary for something that's not even being shown on the page. Perhaps the user might come to this page and never actually show Vanilla Tilt. This can be an opportunity to optimize the performance of our application by utilizing code-splitting.
[00:25] Instead of importing Tilt from Tilt here -- where we are importing our vanilla-tilt library and the Tilt component itself -- we can lazy-load that Tilt component itself using React.lazy. We'll pass a function that returns a dynamic import for Tilt. We're going to assign that to Tilt.
[00:47] Then we can get rid of this import. We're going to render the Tilt component that React.lazy gives us. This relies on the Suspense feature in React. We need to have this Suspense component rendered somewhere above where this Tilt lazy-loaded component is going to be rendered.
[01:03] I'm going to take that Suspense. We'll render it right above the Tilt. We'll give it a fallback value of a div that says, "Loading."
[01:13] With that, I can click on "Show tilt." We'll see that that part of the JavaScript is loaded on demand, saving our users from downloading 3.5 kilobytes if they never actually use this feature.
[01:25] This can be a lot more useful if you're lazy-loading bigger libraries like D3. Let's go ahead and experiment here. I'm going to refresh. I'll switch this to a slow connection.
[01:37] Then if I click on "Show tilt," it shows that loading state fallback. It renders Vanilla Tilt when it's loaded.
[01:45] In review, to make this work, we simply remove the import of Tilt and replaced it with a React.lazy call using a dynamic import. Then we rendered Tilt assuming that it was actually already loaded just as we had before, making no changes to how we're using that component.
[02:01] But then we added the Suspense component from React and rendered that with a fallback value for what it should show while it's busy loading the Tilt component. I should note also that once we've loaded and rendered this one time, any subsequent renders of the Tilt component will render immediately because it's already been loaded.