Use Lazy Routing with React Suspense to Optimize Performance

  • Thread starter Thread starter Asim786521
  • Start date Start date
A

Asim786521

Guest
When we handle asynchronous operations in React, Suspense is mainly used to optimize the UI by placing a placeholder UI during rendering.

Using the Suspense component, the UI can be anything from a simple placeholder to a loading spinner. The fallback is a React node that serves as a lightweight view before the child component runs. Suspense will automatically switch to the fallback when its children are still loading.

πŸ‘‰ The ideal case is when we don’t need to load a component upfront. Instead, we render it only when needed. In most cases, Suspense is used with lazy-loaded components.

πŸ”Ή What is a lazy-loaded component?​


A lazy-loaded component is a performance optimization technique that improves web application speed and efficiency by delaying non-essential resources until they are actually needed by the user.

This feature was introduced in React 16.6.

πŸ”Ή Real Case Example​


I faced this problem when I created a modal component that rendered conditionally based on a specific event.

Inside the modal, there was a child component responsible for:

  • Converting data into a file
  • Uploading the file through a web service

The challenge:

  • The child component’s data was dynamic (changed each time).
  • I noticed a delay in opening the modal because the child component was heavy.
  • The bundle size was also too large.

πŸ”Ή Solution: Suspense + Lazy Loading​


To improve the modal’s performance, I used Suspense with lazy loading:

  1. Changed the child component import to React.lazy, so it only loads when needed.
  2. Wrapped it with Suspense and used a spinner as the fallback UI.

Example Code​


Code:
jsx
import React, { useState, lazy, Suspense } from "react";

// Lazy load the child component
const FileUploader = lazy(() => import("./FileUploader"));

function App() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>

      {isModalOpen && (
        <Modal onClose={() => setIsModalOpen(false)}>
          {/* Wrap lazy-loaded component with Suspense */}
          <Suspense fallback={<div>Loading...</div>}>
            <FileUploader />
          </Suspense>
        </Modal>
      )}
    </div>
  );
}


function Modal({ children, onClose }) {
  return (
    <div className="modal">
      <div className="modal-content">
        <button onClick={onClose}>X</button>
        {children}
      </div>
    </div>
  );
}

export default App;

Continue reading...
 


Join 𝕋𝕄𝕋 on Telegram
Channel PREVIEW:
Back
Top