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 (4)

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

Collapse
 
marlo-bb profile image
ِMarlo Ber

`import React, {useEffect, useState} from 'react'
import axios from 'axios'
import { Link } from 'react-router'
function Home() {
const [characters, setCharacters] = useState([])

useEffect(()=> {
    axios.get('apiurl')
    .then(response =>{
        setCharacters(response.data)
    })
})
Enter fullscreen mode Exit fullscreen mode

return (




hi everyone



welcome




{characters.map(character => (
<div className='bg-white rounded-lg shadow-md overflow-hidden transform transition duration-400 hover:scale-105 hover:shadow-xl'

key={character.id}>



src={character.image}
alt=''
className="w-full h-full object-contain p-4 "
/>

{character.name}

    </Link>

</div>

))}

</div>

)
}`

Collapse
 
marlo-bb profile image
ِMarlo Ber

`
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router';
import { useParams } from 'react-router';

function Details() {
const [user, setUser] = useState(null);
const { id } = useParams();

useEffect(() => {
const fetchCharacter = async () => {
try {
const response = await axios.get(
"fetch datail of each user"
);
const allCharacters = response.data;
const found = allCharacters.find(char => char.id == id);

    if (found) {
      setCharacter(found);
    } else {
      setCharacter(null);
    }
  } catch (error) {
    console.error( error);
  }
};

fetchCharacter();
Enter fullscreen mode Exit fullscreen mode

}, [id]);

if (!users) {
return

Loading ;
}

return (

<div className="p-6">
<div className="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl m-6">
  <div className="md:flex">
    <div className="md:shrink-0">

      <img
        src={user.image}
    alt=''
        className="h-auto w-full object-cover"
      />
    </div>
    <div className="p-8">
    <div>
      <p className='text-lg text-orange-300 font-semibold'>{user.species}</p> 
      <h1 className="block mt-1 text-lg leading-tight font-medium text-black">
        {user.name}
      </h1>
      <p className="mt-2 font-bold text-gray-500">Status: {user.status}</p>
      <p className="mt-2 font-bold text-gray-500">Gender:  {user.gender}</p>
      <p className="mt-2 font-bold text-gray-500">Hair: {user.hair}</p>
      <p className="mt-2 font-bold text-gray-500">Origin: {user.origin}</p>
Enter fullscreen mode Exit fullscreen mode


to="/"
className="mt-4 inline-block bg-black hover:bg-gray-700 text-white font-bold py-2 px-4 rounded"
>
Back

  </div>
</div>
Enter fullscreen mode Exit fullscreen mode


)
}
export default Details;
`