DEV Community

saijami
saijami

Posted on

Boost Your React App Performance with Lazy Loading

🧠 What Is Lazy Loading?
Lazy loading delays loading components, images, or routes until they're actually needed. Instead of bundling your entire app upfront, you load only what the user needs first - improving initial load times and bandwidth usage.

💡 Key Benefits
Faster initial page loads - fewer unused components ship immediately.
Reduced bandwidth usage - only loaded when requested.
Improved user experience - above-the-fold content appears quickly.
Scalable architecture - lazy loading keeps large codebases performant.

description

🛠️ How to Implement Lazy Loading in React
1.Component-Level with React.lazy() + Suspense

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

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

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

2.Route-Based Loading (React Router)

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { lazy, Suspense } from 'react';

const Home = lazy(() => import('./Home'));
const ImagePage = lazy(() => import('./Image'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading page...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/image" element={<ImagePage />} />
        </Routes>
      </Suspense>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

3.Image & Component Libraries

import LazyLoad from 'react-lazyload';

<LazyLoad height={200} once>
  <img src="..." alt="…" />
</LazyLoad>

Enter fullscreen mode Exit fullscreen mode

4.Dynamic Imports with Buttons or Interactions

const LazyProfile = lazy(() => import('./LazyProfile'));

function App() {
  const [showProfile, setShowProfile] = useState(false);

  return (
    <>
      <button onClick={() => setShowProfile(!showProfile)}>
        {showProfile ? 'Hide' : 'Show'} Profile
      </button>
      {showProfile && (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyProfile />
        </Suspense>
      )}
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

✅ Best Practices

  • Lazy-load only non-critical code - e.g., modals, routes, images.
  • Always pair with fallback UI using Suspense.
  • Consider preloading components likely to be used soon.
  • Handle errors gracefully with Error Boundaries.
  • Test on real devices and low-bandwidth connections.

🔚 Final Words
Done right, lazy loading reduces initial payloads, improves perceived responsiveness, and keeps your app scalable. Done poorly, it adds complexity and brittle flows.
Try adding a lazy-loaded route or image to your next React build - it could save your user seconds of load time.

Top comments (0)