SmartCodingTips

⏳ Lazy Loading in React

Lazy loading helps improve performance by loading components only when needed. React provides built-in support using React.lazy and Suspense.


🛠️ 1. React.lazy + Suspense

Use React.lazy to dynamically import a component. Wrap it with Suspense to show a fallback while it loads.


import React, { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./MyComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

📦 2. Code Splitting on Route

Lazy loading is commonly used with routes to avoid loading all pages upfront.


import { BrowserRouter, Routes, Route } from 'react-router-dom';
const About = lazy(() => import('./pages/About'));
const Home = lazy(() => import('./pages/Home'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<p>Loading page...</p>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

💡 3. Tips & Best Practices

  • Only use lazy loading for non-critical components
  • Show a meaningful fallback UI (spinner, skeleton, etc.)
  • Group components into meaningful chunks
  • Combine with route-based code splitting for maximum effect

📁 4. Dynamic Imports vs Static Imports

Unlike regular static imports, dynamic imports with React.lazy() return a Promise and enable deferred loading. This reduces initial bundle size.