Lazy Loading in React: Optimizing App Performance

·

2 min read

Imagine you have a large website with many pages, but you don’t want everything to load at once when the user visits your website. It would be slow and frustrating. Lazy loading helps by only loading parts of the website as needed, instead of all at once.

Real World Example: Think of a movie streaming platform. When you open the platform, you don’t want to load the details for every movie at once, just the ones you see on the home screen. Only when you click on a movie, the details (images, videos, etc.) for that movie load. This saves time and makes the app faster.

Code Example (Step by Step):

  1. Step 1: Setup React project Make sure you have a React app running (use npx create-react-app your-app-name if you don’t have one).

  2. Step 2: Import lazy() and Suspense In React, we use the lazy() function to load components only when they are needed and Suspense to show a loading state while waiting for the component.

  3. Step 3: Code implementation

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

// Lazy load the component
const LazyComponent = lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <h1>Lazy Loading Example</h1>
      {/* Suspense is used to show a fallback (like a loading message) */}
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default App;
  • Explanation:

    • lazy(() => import('./LazyComponent')): This loads the LazyComponent only when it’s needed (when it's rendered).

    • Suspense: We use Suspense to tell React to show a "Loading..." message while the LazyComponent is being fetched.

  1. Step 4: The lazy-loaded component
// LazyComponent.js
import React from 'react';

function LazyComponent() {
  return <div>This is a lazily loaded component!</div>;
}

export default LazyComponent;
  • Explanation: This component will only be loaded when LazyComponent is needed, reducing the initial load time of the app.