DEV Community

Apollo Fredrick
Apollo Fredrick

Posted on

Lazy Loading in React

What is Lazy Loading?

Lazy loading is a technique for asynchronously loading components or resources only when they are needed. This means that instead of downloading the entire application at once, which can lead to slow loading times, especially on slower internet connections, the application only downloads the components that are currently visible to the user. This significantly improves the initial page load and overall user experience.

In this tutorial we are going to learn how to implement Lazy Loading in React.

Prerequisites

You need to have a basic knowledge of React.

Creating the project

We are going to create our React application using Vite and not Create-React-App since Vite is fast.
Run the following command in your project folder.

npm create vite@latest lazy-loading
Enter fullscreen mode Exit fullscreen mode

Select the framework as React and language as Javascript then run the following command to install the dependencies

npm install
Enter fullscreen mode Exit fullscreen mode

Creating components

We are going to create two components, one that will be loaded immediately(Home.jsx) and another that will be loaded lazily(About.jsx)

//Home.jsx
import React from 'react';

const Home = () => {
  return (
    <div>
      <h1>Welcome to Lazy Loading Demo</h1>
      <h2>This component is loaded immediately</h2>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode
//About.jsx
import React from 'react';

const About = () => {
  return (
    <div>
      <h2>This component was lazily loaded!</h2>
    </div>
  );
};

export default About;
Enter fullscreen mode Exit fullscreen mode

Install react-router-dom as we only want to load the lazy component when we navigate to it.

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Create a navigation component with links to the components.

import React from 'react'
import { Link } from 'react-router-dom'

const Navbar = () => {
  return (
    <div>
      <nav>
        <ul>
          <li>
            <Link to="/home">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
        </ul>
      </nav>
    </div>
  )
}

export default Navbar
Enter fullscreen mode Exit fullscreen mode

Modify the App.jsx component as shown below

// App.js
import React, {lazy, Suspense} from 'react'
import {Routes, Route} from 'react-router-dom'
import Navbar from './Navbar'
import Home from './Home'
const About = lazy(() => import('./About'));

function App() {
  return (
    <>
    <Navbar/>
    <Routes>
        <Route path="/home" element={<Home/>} />
        <Route
          path="/about" 
          element={
          <Suspense fallback='Loading...'>
            <About/>
          </Suspense> }/>
      </Routes>
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Wrap the App component in BrowserRouter in the main.jsx as shown below

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { BrowserRouter } from 'react-router-dom'

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>

)
Enter fullscreen mode Exit fullscreen mode

Run your React application using the following command

npm run dev
Enter fullscreen mode Exit fullscreen mode

The Home component is loaded immediately when the root route (/home) is accessed. The About component is loaded lazily when navigating to the /about route.

Conclusion

Lazy loading with react-router-dom is a powerful technique to improve the initial load time of your React applications. By dynamically loading components only when they are needed, you can enhance the user experience and optimize the performance of your application. Consider applying lazy loading to larger components or those that are not crucial for the initial view, ensuring a smoother user interaction.

Top comments (2)

Collapse
 
hazush profile image
hazush

Thank you very much bro. Gonna test it out

Collapse
 
teddapollo profile image
Apollo Fredrick

Welcome bro, try it out