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: www.shopflamingo.com.
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.