DEV Community

Cover image for How to lift your React App performance using Lazy Loading?
Ibrahima Ndaw
Ibrahima Ndaw

Posted on • Updated on • Originally published at ibrahima-ndaw.com

How to lift your React App performance using Lazy Loading?

Originally posted on my blog

React, as you already know is a JavaScript a library for building user interfaces. And when we develop React apps, we build a lot of components that will be bundled into one file at the end. Depending on the size of our files and third-party libraries it can be really big, even if the building part will minify it and reduce the size.
However, that bundle size can be optimized again with a technic called Lazy Loading.

In this tutorial, we will learn how to lift a React App performance using Lazy Loading.

Prerequisites

This tutorial assumes that you have at least a basic to mid-level knowledge of React and React Router, I will only focus on the Lazy Loading part.

If you need to get started with the React Router, this tutorial might help you, otherwise, let's do the prerequisites.

To be able to follow along, you'll have to clone the repo of the project by running in your terminal:

git clone https://github.com/ibrahima92/prep-react-lazy-loading
Enter fullscreen mode Exit fullscreen mode

And run npm install in your terminal to install the dependencies.

Then, If you've done with the prerequisites, let's start loading our components lazily.

What is Lazy Loading?

Lazy loading or code splitting is the ability to defer the loading of a chunk of code. That means, instead of bundling and load all the code when the page loads, just the needed code will be loaded, and some parts will be loaded whenever it's needed.

When do we need Lazy Loading?

Code splitting is useful for medium size to larger React apps. Even in some medium-size apps, we don't need lazy loading.

If you have some parts of your app where most of your users won't visit, it makes sense to load it lazily instead of increasing your bundle size and hence, decreasing the performance of your app.

In this tiny project, lazy loading is overkill, to be honest, but it's always much simpler to learn how to do these kinds of things with a mini-project.

Now, let's start loading our component lazily.

How to lazy load a component?

Before React 16.6, Lazy loading was done either with Higher-Order Component (HOC) or a library. Now, loading a component lazily is much easier with React lazy and React Suspense. However, React Lazy doesn't support named exports and server-side rendering.

It's also good to know that Code Splitting is an advanced concept, and some bundlers don't support it. create-react-app has a really good and modern configuration, use it as possible as you can.

So, let's update the App.js file a bit to see them in action.

  • In App.js
import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import NavBar from './components/NavBar';
import Posts from './components/Posts/Posts';
const Users = lazy(() => import('./components/Users/Users')) 

function App() {

  return (
    <BrowserRouter>
      <main>
      <NavBar />
      <Switch>
        <Route exact path="/" component={Posts}  />
        <Route path="/users" render={() =>
          <Suspense fallback={<h1>Loading....</h1>}>
            <Users />
          </Suspense>
        }/>
      </Switch>
      </main>
    </BrowserRouter>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

As you can see here, we start by importing lazy and Suspense from the React library. Then, instead of importing the Users component, we use lazy to be able to defer it and import the needed component dynamically when needed.

With that change and the help of Suspense, we can now use the render props provided by React Router to display the component once imported and if it takes time to load, it will use the fallback to show a loading message.

By the way, for the fallback property you're not limited to a simple message you can use a spinner component, loading indicator, etc.

Now, to see what's changed you need to open your browser devtools and check the Network tab, then, you'll see that when you click on the Users page, a new chunk of data will be loaded.

image-cache

With that change, we have now successfully loaded a component lazily using React Lazy and React Suspense.

Conclusion

Lazy Loading is a good way to increase performance in a React App. It's really useful in some cases and definitely, something to know and use, however, using it when not needed can cause some performance issues.

Photo by Kate Stone Matheson on Unsplash

Top comments (6)

Collapse
 
monfernape profile image
Usman Khalil

I love how you explain difficult concepts while keeping things very simple.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Amazing! I really love your comment. Thanks.

Collapse
 
tacocat profile image
Minhee Kim

Best tutorial on react lazy loading ever👍 It was so easy to understand. Can I translate your post into korean and repost it on my blog? I'll reveal the source(your dev blog url).

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks. Of course, you can translate it, and thanks for sharing.

Collapse
 
xarala221 profile image
Ousseynou Diop

great tutorial.
The concept is well explained.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks a lot man!