Asynchronous rendering via React.Suspense

Asynchronous rendering via React.Suspense

 Asynchronous rendering via React.Suspense

React.Suspense Explained

React.Suspense is a component in React that allows you to handle asynchronous rendering in a declarative way. It is primarily used for code splitting (lazy loading) and handling asynchronous data fetching in modern React applications.

When to Use React.Suspense

You should use React.Suspense when:

  1. Lazy Loading Components – When you dynamically import a component using React.lazy(), React.Suspense provides a fallback UI while the component loads.

  2. Data Fetching with React Server Components – In React 18+, Suspense is used to defer rendering until data is available.

  3. Streaming Server-Side Rendering (SSR) – Helps optimize the hydration process in server-rendered applications.

Example Use Cases

1. Lazy Loading Components

This is useful for reducing bundle size and improving performance.

jsx
import React, { Suspense, lazy } from "react"; const LazyComponent = lazy(() => import("./LazyComponent")); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); } export default App;

👉 Here, LazyComponent is loaded asynchronously, and while it is being fetched, "Loading..." is displayed.


2. Handling Async Data Fetching (React 18)

With React 18 concurrent features, you can use Suspense for data fetching.

jsx
import { Suspense } from "react"; import { fetchUserData } from "./api"; const UserProfile = ({ userId }) => { const user = fetchUserData(userId); // Assume this is an async function return <div>{user.name}</div>; }; function App() { return ( <Suspense fallback={<div>Loading user data...</div>}> <UserProfile userId={1} /> </Suspense> ); }

👉 This will delay rendering UserProfile until fetchUserData resolves.


Key Takeaways

  • Suspense is not for handling regular Promises; it's mainly for integration with React.lazy or concurrent React features like React Server Components.

  • It allows you to show a fallback UI while waiting for async resources.

  • In React 18, it improves SSR and concurrent rendering performance.

Would you like more advanced examples or integration with libraries like React Query? 🚀

Comment