paint-brush
Boosting React App Performance: A Guide to Lazy Loading and Suspenseby@ljaviertovar
1,153 reads
1,153 reads

Boosting React App Performance: A Guide to Lazy Loading and Suspense

by L Javier Tovar
L Javier Tovar HackerNoon profile picture

L Javier Tovar

@ljaviertovar

☕ Full Stack developer 👨‍💻 Indie maker ✍️ Tech writer

October 3rd, 2023
Read on Terminal Reader
Read this story in a terminal
Print this story
Read this story w/o Javascript
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Lazy loading is a strategy that defers the loading of non-essential resources until they are needed. It reduces the initial loading time and improves the overall performance of the application. In React, we can achieve lazy loading using the`lazy` function and the `Suspense`  component.
featured image - Boosting React App Performance: A Guide to Lazy Loading and Suspense
1x
Read by Dr. One voice-avatar

Listen to this story

L Javier Tovar HackerNoon profile picture
L Javier Tovar

L Javier Tovar

@ljaviertovar

☕ Full Stack developer 👨‍💻 Indie maker ✍️ Tech writer

Learn More
LEARN MORE ABOUT @LJAVIERTOVAR'S
EXPERTISE AND PLACE ON THE INTERNET.
0-item
1-item

STORY’S CREDIBILITY

Code License

Code License

The code in this story is for educational purposes. The readers are solely responsible for whatever they build with it.

DYOR

DYOR

The writer is smart, but don't just like, take their word for it. #DoYourOwnResearch before making any investment decisions or decisions regarding your health or security. (Do not regard any of this content as professional investment advice, or health advice)

In modern web development, optimizing the performance of our applications is crucial to provide a smooth user experience. An effective technique to achieve this is lazy loading, which involves loading only the necessary components and resources when they are actually required.


In this blog, we will explore how to implement lazy loading in React using the lazy function and the Suspense component, and we will see the benefits it brings to our applications.

Understanding Lazy Loading

Lazy loading is a strategy that defers the loading of non-essential resources until they are needed, reducing the initial loading time and improving the overall performance of the application. In React, we can achieve lazy loading using the lazy function and the Suspense component, introduced in React 16.6.

Using the lazy Function

The lazy function allows us to dynamically import a component, which is especially useful for code splitting and optimizing package size.

Here's how you can use it:


const MyLazyComponent = React.lazy(() => import('./MyComponent'));


In this example, MyComponent will only be loaded when MyLazyComponent is rendered in the application.


Implementing Lazy Loading with the Suspense Component. The Suspense component is used to wrap components that are lazily loaded. It allows us to specify a fallback content that will be displayed while the lazy component is loading.


Here's how it's used:


import React, { lazy, Suspense } from 'react';

const MyLazyComponent = lazy(() => import('./MyComponent'));

function App() {
  return (
    <div>
      <h1>Lazy Loading Example</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <MyLazyComponent />
      </Suspense>
    </div>
  );
}


In this example, while MyLazyComponent is being fetched, the fallback content ("Loading...") will be shown, providing a smooth transition for the user.

Benefits of Lazy Loading

  1. Faster Initial Loading: By loading only the necessary components, the initial loading time of the application is reduced, enhancing the user experience.


  2. Performance Improvement: Lazy loading avoids unnecessary loading of resources, which can lead to faster navigation and interactions within the application.


  3. Code Splitting: Lazy loading encourages code splitting, resulting in smaller package sizes that load more efficiently.


  4. Increased User Engagement: Users can interact with visible components more quickly, improving engagement and interaction.más rápidamente, mejorando la participación y la interacción.

Let’s Code a Real Example

Imagine we are working on a web application containing several pages or routes, each represented by a different component. We want to optimize the application’s performance by ensuring that components are loaded only when the user needs them.


article preview
CODESANDBOX

priceless-pond-38qfks - CodeSandbox

priceless-pond-38qfks by ljaviertovar using loader-utils, react, react-dom, react-router-dom, react-scripts


In the previous example, HomePageAboutPage, and ContactPage are components created using lazy and the import() function. This allows the components to be loaded lazily, meaning only when needed.


The lazy() function receives a function that returns a promise that loads the component.

Within Suspense, routes are defined using the Routes component. This component contains several Route elements that define the different routes of the application.


Each Route has a path corresponding to the URL and element representing the component to be rendered when the URL matches the path.


If you want to learn more about React Router you can check out my other article:


article preview
HACKERNOON

Using React Router v6 for Private and Public Routes with Access Validation | HackerNoon

In essence, React Router is a routing library designed for React-based web applications. Its main purpose is to facilitate navigation between components or view


Conclusion

Lazy loading is a powerful technique in React to enhance performance and user experience in our applications. By utilizing the lazy function and the Suspense component, we can efficiently load components on demand, leading to faster loading times and more responsive applications.




Read more:


Want to connect with the Author?

Love connecting with friends all around the world on Twitter.


Also published here.

L O A D I N G
. . . comments & more!

About Author

L Javier Tovar HackerNoon profile picture
L Javier Tovar@ljaviertovar
☕ Full Stack developer 👨‍💻 Indie maker ✍️ Tech writer

TOPICS

THIS ARTICLE WAS FEATURED IN...

Permanent on Arweave
Read on Terminal Reader
Read this story in a terminal
 Terminal
Read this story w/o Javascript
Read this story w/o Javascript
 Lite
Ljaviertovar
X REMOVE AD