Reader small image

You're reading from  React and React Native - Fourth Edition

Product typeBook
Published inMay 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781803231280
Edition4th Edition
Languages
Right arrow
Authors (3):
Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

Roy Derks
Roy Derks
author image
Roy Derks

Roy Derks is a serial start-up CTO, international speaker, and author from the Netherlands. He has been working with React, React Native, and GraphQL since 2016. You might know him from the book “React Projects – Second Edition”, which was released by Packt earlier this year. Over the last few years, he has inspired tens of thousands of developers worldwide through his talks, books, workshops, and courses.
Read more about Roy Derks

Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

View More author details
Right arrow

Chapter 10: Code Splitting Using Lazy Components and Suspense

Code splitting has been happening in React applications for some time now, long before there was any official support in the React API. With the latest version of React, there are new APIs that we can use that directly support code-splitting scenarios. Code splitting is necessary when you have larger applications with a lot of JavaScript code that must be delivered to a browser.

Big monolithic JavaScript bundles that house an entire application can create usability issues on initial page loads due to longer load times. With code splitting, we have more fine-grained control over how code makes its way from the server to the browser. This means more opportunities for us to properly handle load-time User Experience (UX).

In this chapter, you'll learn how to do this in your React applications by using the lazy() API and the Suspense components, two recent additions to React. Once you understand how these two pieces...

Technical requirements

You can find the code files of this chapter on GitHub at https://github.com/PacktPublishing/React-and-React-Native-4th-Edition/tree/main/Chapter10.

Using the lazy API

There are two pieces involved with using the new lazy() API in React. First, there's bundling components into their own separate files so that they can be downloaded by the browser separately from other parts of the application. Second, once you have created the bundles, you can build React components that are lazy – they don't download anything until the first time they're rendered. Let's look at both of these.

Dynamic imports and bundles

The code examples in this book use the create-react-app tooling for creating bundles. The nice thing about this approach is that you don't have to maintain any bundle configuration. Instead, bundles are created for you automatically, based on how you import your modules. If you're using the import statement everywhere, your app will be downloaded all at once in one bundle. When your app gets bigger, there will likely be features that some users never use or don't use as frequently...

Using the Suspense component

In this section, we'll explore some of the more common usage scenarios of the Suspense component. We'll look at where to place Suspense components in your component tree, how to simulate latency when fetching bundles, and some of the options available to us to use as the fallback content.

Top-level Suspense components

Lazy components need to be rendered inside of a Suspense component. However, they do not have to be direct children of Suspense though, which is important because this means that you can have one Suspense component handle every lazy component in your app. Let's illustrate this concept with an example. Here's a component that we would like to bundle separately and use lazily:

export default function MyFeature() {
  return <p>My Feature</p>;
}

Next, let's make the MyFeature component lazy and render it inside of a MyPage component:

const MyFeature = React.lazy(() => import("...

Avoiding lazy components

It might be tempting to make most of your React components lazy components that live in their own bundle. After all, there isn't much extra work that needs to happen to set up separate bundles and make lazy components. However, there are some downsides to this. If you have too many lazy components, your app will end up making several HTTP requests to fetch them – at the same time. There's no benefit to having separate bundles for components used on the same part of the app. You're better off trying to bundle components together in a way that one HTTP request is made to load what is needed on the current page.

A helpful way to think of this is to associate "pages" with bundles. If you have lazy page components, everything on that page will also be lazy yet bundled together with other components on the page. Let's build an example that demonstrates how to organize our lazy components. Let's say that your app has a...

Exploring lazy pages and routes

In the Avoiding lazy components section, you saw where to avoid making components lazy when there is no benefit in doing so. The same pattern can be applied when you're using react-router as the mechanism to navigate around your application. Let's take a look at an example. Here are the imports we'll need:

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  Outlet,
} from "react-router-dom";
import { FadeLoader } from "react-spinners";
Next, we'll create our lazy components:
const First = React.lazy(() =>
  Promise.all([
    import("./First"),
    new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 3000);
    }),
  ]).then...

Summary

This chapter was all about code splitting and bundling, which are important concepts for larger React applications. We started by looking at how code is split into bundles in your React applications by using the import() function. Then, we looked at the lazy() React API and how it helps to simplify loading bundles when components are rendered for the first time. Next, we looked more deeply at the Suspense component, which is used to manage content while component bundles are being fetched. The fallback property is how we specify the content to be shown while bundles are being loaded. You typically don't need more than one Suspense component in your app, as long as you follow a consistent pattern for bundling pages of your app.

In the next chapter, you'll learn how to use the Next.js framework to handle rendering React components on the server. The Next.js framework allows you to create pages that act as React components and can be rendered on the server and in...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fourth Edition
Published in: May 2022Publisher: PacktISBN-13: 9781803231280
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (3)

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

author image
Roy Derks

Roy Derks is a serial start-up CTO, international speaker, and author from the Netherlands. He has been working with React, React Native, and GraphQL since 2016. You might know him from the book “React Projects – Second Edition”, which was released by Packt earlier this year. Over the last few years, he has inspired tens of thousands of developers worldwide through his talks, books, workshops, and courses.
Read more about Roy Derks

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk