React Advanced

0% completed

Previous
Next
Lazy Loading Routes and Components

In React applications that use React Router for routing, you can implement lazy loading for routes by dynamically importing components associated with each route. In large applications, different pages (routes) often have their own components. Instead of loading all routes upfront, we can load them dynamically as users navigate.

Example

Here's how we can use React Router with lazy loading via React.lazy and Suspense:

import React, { Suspense, lazy } from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; const Home = lazy(() => import('./Home')); const About = lazy(() => import('./About')); const Contact = lazy(() => import('./Contact')); function App() { return ( <Router> <Suspense fallback={<p>Loading Page...</p>}> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </Suspense> </Router> ); } export default App;

In this code,

  • The Home, About, and Contact components are lazy-loaded.
  • They are only fetched when the user navigates to their respective routes.
  • The Suspense fallback UI is displayed while the component is loading.

Lazy Loading Components in Nested Routes

Lazy loading can be applied within nested components too. For example, if an AdminPanel has different sections, we can load them dynamically:

const AdminDashboard = lazy(() => import('./AdminDashboard')); const UserManagement = lazy(() => import('./UserManagement')); function AdminPanel() { return ( <Suspense fallback={<p>Loading Admin Panel...</p>}> <Routes> <Route path="dashboard" element={<AdminDashboard />} /> <Route path="users" element={<UserManagement />} /> </Routes> </Suspense> ); }

Lazy loading is a crucial optimization technique for improving React application performance. By implementing lazy loading for components and routes, you can reduce initial page load time, optimize JavaScript bundle size and improve user experience.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next