Reader small image

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

Product typeBook
Published inApr 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781805127307
Edition5th Edition
Languages
Tools
Right arrow
Authors (2):
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

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

View More author details
Right arrow

Code Splitting Using Lazy Components and Suspense

Code splitting has been a significant part of React applications for many years, even before official support was included in the React API. The evolution of React has brought about APIs that are specifically designed to assist in code-splitting scenarios. Code splitting becomes crucial when dealing with large applications containing a vast amount of JavaScript code that needs to be delivered to a browser.

In the past, monolithic JavaScript bundles containing an entire application could cause usability issues due to long initial page load times. Thanks to code splitting, we now have much more granular control over how code is transferred from the server to the browser. This gives us ample opportunities to optimize load-time User Experience (UX).

In this chapter, we will revisit how to implement this in your React applications by using the lazy() API and the Suspense components. These features are very powerful tools in the...

Technical requirements

You can find the code files of this chapter on GitHub at https://github.com/PacktPublishing/React-and-React-Native-5E/tree/main/Chapter08.

Using the lazy API

There are two pieces involved with using the 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 they are needed. Let’s look at both of these.

Dynamic imports and bundles

The code examples in this book use the Vite 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 plain import statement (not to be confused with the import method) 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’...

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 couple of...

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:

const First = React.lazy(() => import("./First"));
const Second = React.lazy(() => import("./Second"));
function Layout() {
  return (
    <section>
      <nav>
        <span>
          <Link to="first">First</Link>
        </span>
        <span> | </span>
        <span>
          <Link to="second">Second</Link>
        </span>
      </nav>
      <section>
        <React.Suspense fallback={<FadeLoader color="lightblue" />}>
          <Outlet />
        </React.Suspense...

Summary

This chapter was all about code splitting and bundling, which are important concepts for large 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...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127307
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 (2)

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

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