Use cases of React Suspense
1. Revealing nested components while data is loading
When component suspends, the closest parent suspense shows the fallback. So, we can use multiple Suspense components to show multiple loading states.
//App.tsx
import { Suspense } from "react";
import "./App.css";
import AsyncComponent from "./async-comp";
import AnotherAsyncComponent from "./another-async-comp";
function App() {
return (
<Suspense fallback={<div>Loading 1 ...</div>}>
<AnotherAsyncComponent />
<Suspense fallback={<div>Loading 2 ...</div>}>
<AsyncComponent />
</Suspense>
</Suspense>
);
}
export default App;
//another-async-comp.tsx
import fetchData from "./api/fetch-data";
const promise = fetchData<{ title: string; userId: string }>(
"https://jsonplaceholder.typicode.com/todos/1"
);
export default function AnotherAsyncComponent() {
const data = promise.read();
return (
<div>
<h1>{data.title}</h1>
<p>User Id: {data.userId}</p>
</div>
);
}
React.lazy() with React Suspense
In react, Lazy loading means when a component react only renders the component we it is needed.
- When the button is clicked for the first time and show becomes true, <LazyComp /> is displayed.
- lazy () creates a dynamic import for <LazyComponent />. Loading lazy components is an asynchronous task and while the code for the lazy component is still loading, attempting to render it will suspend.
- We are wrapping it with Suspense to show the fallback UI while it is loading.
The syntax for lazy loading a component is given below.
//App.tsx
import { Suspense, lazy, useState } from "react";
import "./App.css";
const LazyComp = lazy(() => import('./LazyComp.ts'));
function App() {
const [show, setShow] = useState(false)
return (
<main>
<h1>React Lazy Demo</h1>
<button onClick={() => setShow(!show)}>
{show ? "Hide" : "Show"}
</button>
<Suspense fallback={<p>Loading...</p>}>
<LazyComp />
</Suspense>
</main>
);
}
export default App;
2. Using Error Boundary to show error state
Suspense is for showing fallback UI while component is doing an asynchronous operation but what if operation fails. React gives use <ErrorBoundary /> to show fallback UI when error occurs. Currently can only define this using class component but we have libraries to do the same in functional components.
Install the the library using the command
npm i react-error-boundary
In the below example, if the asynchronous operation fails, error will render the fallback UI.
//App.tsx
import { Suspense } from "react";
import { ErrorBoundary } from 'react-error-boundary';
import "./App.css";
import AsyncComponent from "./async-comp";
function App() {
return (
<ErrorBoundary
fallback={<div>Error occured.</div>}>
<Suspense fallback={<p>Loading...</p>}>
<AsyncComponent />
</Suspense>
</ErrorBoundary>
);
}
export default App;
3. Suspense with Concurrent Rendering
Concurrent rendering in React, introduced in React 18, allows for simultaneous handling of multiple tasks, improving performance and responsiveness. With a priority-based scheduler, high-priority tasks are executed first, optimizing resource utilization and enhancing user experience. Concurrent rendering is particularly beneficial in applications where UI rendering and data processing occur together, resulting in smoother transitions and faster load times.
Server-side applications can utilize Suspense to stream data efficiently, displaying content as it becomes available. However, due to its experimental nature and ongoing changes, concurrent rendering should be approached with caution in production applications. Developers should stay informed about updates and modifications for compatibility and stability.
Concurrent rendering addresses previous limitations in React’s rendering model, enabling interruptible rendering and improved handling of complex UI updates. But for now developers should not use it in production application as it is constantly changing.
How does Suspense help in Handling Asynchronous Operations in React ?
Suspense, first introduced in React 16, is a feature that aims to enhance the user experience by managing asynchronous operations. It simply lets you render a fallback UI decoratively while the child component is waiting for any asynchronous task to be completed.
Table of Content
- What is React Suspense?
- Project Initialisation
- Traditional Data Fetching Techniques
- How Suspense works?
- Use cases of React Suspense
- Suspense with Server Components in Next.js
- Conclusion