How to use React.Lazy
React 16.6.0 introduced
React.lazy, which allows you to code-split using the new Suspense API.
Siddharth Kshetrapal came out with a great video showing how this works in 60 seconds. I’d recommend watching it –– it’s really well-done.
I’ve built a Github clone based off of Siddharth’s example. Hopefully this will help people who prefer reading to watching videos, or who to be walked through it step by step!
Why would I use React.lazy?
React.lazy allows developers to block UI from rendering until a pre-determined condition is met. For example, maybe you don’t want your component to render until you get a response back from an endpoint.
Before React.lazy, you had to load all of the files that were ever going to be visible in that view, even if some of them were hidden.
For example, imagine you built an e-commerce site like I’m working on at Harry's:
In the upper-right hand corner, we have a cart icon. When you click it, a
PanelOverlay component slides out from the right-hand side.
Right now, we load the
PanelOverlay component when we load
/. But with
React.lazy, we could dynamically import that component so that it’s only being loaded after it has been clicked! That should allow us to load the homepage even more quickly.
You might be wondering how lazy() is different from react-loadable, for example. Sean T. Larkin explains it well in this tweet:<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Well lazy() let's you not need a separate library to have easy code splitting. It's now out of the box through React.lazy. what loadable-component and react-universal-component do in addition handle some SSR stuff. They should also just use the lazy() API instead internally.</p>— Sean Thomas Larkin (肖恩) (@TheLarkInn) <a href="https://twitter.com/TheLarkInn/status/1055577625106644992?ref_src=twsrc%5Etfw">October 25, 2018</a></blockquote>
lazy() lets you code-split without adding another dependency to your codebase. It makes a best practice (code-splitting) easier, which will encourage developer to use it, and will make writing performant React apps more seamless.
Let’s Take a Look at an Example
I built a demo of code-splitting with
React.lazy using Github’s API to show you exactly how to implement it in your own application.
Below is a .gif of how code-splitting would look on a low-end mobile device. I slowed down so it’s easy to see every distinct step of the process.
Let’s walk through what’s happening here:
- I load the name of the application and a search bar.
- I search for a Github username.
- My application fetches data from Github’s API and renders the username.
- The application dynamically imports the Repos component.
- While the application waits for the Repos component to load, it displays a blurred out “fallback” UI.
- The Repos component loads.
Let’s also take a look at the network tab so you can see the code-splitting in action.
When we don’t code-split, two chunks are loaded immediately.
On the other hand, when we implement code-splitting, we load two chunks initially, and then a third once we actually search for a Github username.
How Does It Work?
The best part about this React feature is how easy it is to implement.
Let’s start with a simple implementation example. @ggrgur provided an awesome example on twitter:<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">🔥🔥Asynchronously | Dynamically | Lazy 🔥🔥 loading component with <a href="https://twitter.com/hashtag/React?src=hash&ref_src=twsrc%5Etfw">#React</a> Suspense and <a href="https://twitter.com/webpack?ref_src=twsrc%5Etfw">@webpack</a> with proper code splitting <br><br>This is *the* reason to upgrade to ⭐️<a href="https://twitter.com/reactjs?ref_src=twsrc%5Etfw">@reactjs</a> 16.6⭐️ <a href="https://t.co/qN3WkmoTPL">pic.twitter.com/qN3WkmoTPL</a></p>— Grgur Grisogono (@ggrgur) <a href="https://twitter.com/ggrgur/status/1055412110895841280?ref_src=twsrc%5Etfw">October 25, 2018</a></blockquote>
There are three important pieces to code-splitting in React:
- Importing Suspense and lazy from React.
- Dynamically importing the file you want to defer loading
- Wrapping that component in Suspense and setting a fallback UI.
And now I’ll share an entire example:
Do you want design systems tips and tricks sent to your inbox?