DEV Community

Md Yusuf
Md Yusuf

Posted on

Lazy Loading Components in React Router: A Step-by-Step Guide

Lazy loading with React Router is useful for optimizing your React app by loading components only when they are needed, rather than loading everything upfront. You can achieve this using React.lazy and Suspense. Hereโ€™s an example of how you can implement lazy loading with React Router:

Steps:

  1. Install React Router (if not already installed):
   npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode
  1. Code Example:
   import React, { Suspense, lazy } from 'react';
   import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

   // Lazy load components
   const Home = lazy(() => import('./Home'));
   const About = lazy(() => import('./About'));
   const Contact = lazy(() => import('./Contact'));

   function App() {
     return (
       <Router>
         {/* Suspense allows you to show a fallback (like a loading spinner) while loading */}
         <Suspense fallback={<div>Loading...</div>}>
           <Routes>
             <Route path="/" element={<Home />} />
             <Route path="/about" element={<About />} />
             <Route path="/contact" element={<Contact />} />
           </Routes>
         </Suspense>
       </Router>
     );
   }

   export default App;
Enter fullscreen mode Exit fullscreen mode

Breakdown:

  • React.lazy: This is used to dynamically import the components.
  • Suspense: It wraps your routes and shows a fallback component (like a spinner or text) until the lazy-loaded component is ready.
  • Routes: Defines the routes that correspond to the lazy-loaded components.

This method improves performance by loading routes and components only when they are accessed, which is great for large applications.

Top comments (0)