DEV Community

Kawan Idrees
Kawan Idrees

Posted on

React Performance Optimization : Lazy Loading and Code Splitting

Introduction:
Code splitting is a powerful technique used to optimize web application performance by breaking down the bundle into smaller chunks that can be loaded on demand. This approach reduces the initial load time, improves user experience, and minimizes resource usage. React, a popular JavaScript library for building user interfaces offers a built-in method for code splitting using dynamic imports. In this guide, we will explore how to implement code splitting with dynamic imports in a React application, along with a comprehensive code example.

let's dive deep into it:

Step 1: Setting Up a React Application
To get started, ensure that you have a basic React application set up. You can use tools like Create React App or set up a minimal React project manually. Once you have a React project ready, proceed to the next steps.

Step 2: Install Required Dependencies
Open your project in a terminal and install the necessary dependencies using npm or yarn.

# Using npm
npm install react-router-dom

# Using yarn
yarn add react-router-dom

Enter fullscreen mode Exit fullscreen mode

Step 3: Creating Routes
For this code splitting example, let's assume we have a simple application with two routes: Home and About. We will dynamically load the About component when the user navigates to the About page. Open your App.js file and add the following code:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

const Home = () => <h2>Welcome to the Home page</h2>;

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

const App = () => {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
        </ul>
      </nav>
      <React.Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
        </Switch>
      </React.Suspense>
    </Router>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

In the code above, we import the BrowserRouter, Route, Switch, and Link components from react-router-dom. We define the Home component as a regular component, but the About component is loaded dynamically using React.lazy and import(). We wrap the component with to show a loading indicator while the component is being loaded.

Step 4: Create the About Component
Now, let's create the About.js file in the same directory as App.js with the following code

import React from 'react';

const About = () => <h2>Welcome to the About page</h2>;

export default About;

Enter fullscreen mode Exit fullscreen mode

Step 5: Build and Run the Application
Once you've completed the previous steps, you can build and run your application. In the terminal, run the following command:

# Using npm
npm run build

# Using yarn
yarn build

Enter fullscreen mode Exit fullscreen mode

After the build process finishes, you can start your application:

# Using npm
npm start

# Using yarn
yarn start
Enter fullscreen mode Exit fullscreen mode

Conclusion:
Code splitting with dynamic imports is a powerful technique that can significantly improve the performance of your React application by reducing the initial load time. By splitting your bundle into smaller chunks and loading them on-demand, you can provide a faster and smoother user experience. In this guide, we explored how to implement code splitting with dynamic imports in a React

Top comments (6)

Collapse
 
m0slah profile image
MO Slah

Thank U Kawan

Collapse
 
maddy profile image
Maddy

Welcome to the community!

Collapse
 
rahenmohammed profile image
Rahen-Mohammed

Thank you for this information๐Ÿ‘๐Ÿ‘

Collapse
 
kawanedres profile image
Kawan Idrees

You are welcome

Collapse
 
roody_ridar2_9abf58aeb336 profile image
Roody Ridar2

Thanks for the info. Should I make every route in my React project lazy loading?

Collapse
 
kawanedres profile image
Kawan Idrees

lazy loading helps you to optimize initial render of the project rendering life cycle if initial load render time is your concern absolutely you have to do it