0
0
ReactHow-ToBeginner · 4 min read

How to Use Lazy Loading in React for Faster Apps

In React, use React.lazy() to load components lazily and wrap them with Suspense to show a fallback UI while loading. This delays loading parts of your app until they are needed, improving performance.
📐

Syntax

Use React.lazy(() => import('./Component')) to define a lazy-loaded component. Wrap it inside <Suspense fallback="Loading..."> to show a loading message or spinner while the component loads.

  • React.lazy(): Dynamically imports the component.
  • Suspense: Handles the loading state with a fallback UI.
jsx
import React, { Suspense } from 'react';

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

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

export default App;
Output
Displays 'Loading...' while LazyComponent loads, then shows LazyComponent content.
💻

Example

This example shows a button that toggles the display of a lazily loaded component. The component only loads when the user clicks the button, saving initial load time.

jsx
import React, { useState, Suspense } from 'react';

const LazyMessage = React.lazy(() => import('./LazyMessage'));

function App() {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide' : 'Show'} Message
      </button>
      <Suspense fallback={<div>Loading message...</div>}>
        {show && <LazyMessage />}
      </Suspense>
    </div>
  );
}

export default App;

// LazyMessage.js
// export default function LazyMessage() {
//   return <div>Hello from the lazy loaded component!</div>;
// }
Output
Button toggles showing 'Hello from the lazy loaded component!' after showing 'Loading message...' while loading.
⚠️

Common Pitfalls

  • Not wrapping lazy components in Suspense causes errors.
  • Using lazy loading for very small components can add unnecessary complexity.
  • Lazy loading only works for default exports, so named exports require extra handling.
  • Not providing a meaningful fallback UI can confuse users during loading.
jsx
/* Wrong: Missing Suspense wrapper */
const LazyComp = React.lazy(() => import('./Comp'));

function App() {
  return <LazyComp />; // This will cause an error
}

/* Right: Wrap with Suspense */
import React, { Suspense } from 'react';

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

Quick Reference

  • React.lazy(): Use to import components lazily.
  • Suspense fallback: UI shown while loading lazy components.
  • Works only with default exports.
  • Best for large components or routes.

Key Takeaways

Always wrap lazy-loaded components with Suspense and provide a fallback UI.
Use React.lazy() to import components only when needed to improve app speed.
Lazy loading works only with default exports, so export components accordingly.
Avoid lazy loading very small components to keep code simple.
Provide clear loading indicators to improve user experience during lazy loading.