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
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.
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.
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:
The challenge:
To improve the modalβs performance, I used Suspense with lazy loading:
Continue reading...
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.
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:
- Changed the child component import to
React.lazy
, so it only loads when needed. - 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...