Suspense in React – Detailed Notes
Course: React JS Training
Topic: Understanding Suspense, fallback UI, lazy loading, nested Suspense boundaries, practical examples, and best practices.
1. Introduction to Suspense
Suspense is a built-in React component that allows an application to display a fallback UI while certain content is waiting to become ready. For example, a website can display a loading message, spinner, or skeleton screen while a lazily loaded component is being downloaded.
Suspense helps developers manage loading states and control when different parts of the user interface become visible. It is commonly used with React's lazy() function to load components only when they are needed.
Official documentation: React Suspense Documentation
2. What Is the Purpose of Suspense?
- Display a loading indicator while supported content is loading.
- Work with lazy-loaded React components.
- Improve the perceived responsiveness of an application.
- Control when groups of components appear together.
- Support nested loading boundaries for different sections of a page.
- Work with Suspense-enabled data-loading frameworks and supported React APIs.
3. Basic Syntax of Suspense
The Suspense component accepts two important props: children and fallback.
import { Suspense } from 'react';
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<MyComponent />
</Suspense>
);
}
export default App;
Explanation:
Suspense: Defines a boundary around content that may suspend while rendering.
fallback: Defines what React should display while the child content is not ready.
MyComponent: The component React attempts to render.
When the child suspends, React displays the fallback. When the child becomes ready, React displays the actual content.
4. Understanding the fallback Prop
The fallback prop accepts any valid React node, such as text, JSX, a loading spinner, or a skeleton component.
Example 1: Text fallback
import { Suspense, lazy } from 'react';
const Profile = lazy(() => import('./Profile'));
function App() {
return (
<Suspense fallback={<p>Loading profile...</p>}>
<Profile />
</Suspense>
);
}
export default App;
Example 2: Custom loading component
import { Suspense, lazy } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
function Loading() {
return <div className="loading">Please wait, loading dashboard...</div>;
}
function App() {
return (
<Suspense fallback={<Loading />}>
<Dashboard />
</Suspense>
);
}
export default App;
In the second example, the reusable Loading component provides the fallback interface.
5. Suspense with Lazy Loading
One of the most common uses of Suspense is loading components on demand. React's lazy() function delays loading a component's code until React first attempts to render it.
Example
import { Suspense, lazy } from 'react';
const About = lazy(() => import('./About'));
function App() {
return (
<div>
<h1>My React Application</h1>
<Suspense fallback={<p>Loading About page...</p>}>
<About />
</Suspense>
</div>
);
}
export default App;
How it works:
- React attempts to render the
About component.
- The component's code is loaded through the dynamic
import().
- If the component suspends while loading, React displays the fallback.
- When the component is ready, React renders the About page.
Important: The lazy-loaded component should normally be a default export. Declare lazy() components outside other component functions to avoid unexpected remounting and state resets.
Related documentation: React lazy() Documentation
6. Difference Between Suspense and lazy()
| Feature |
Suspense |
lazy() |
| Type |
React component |
React function |
| Main purpose |
Displays fallback UI when supported children suspend |
Defers loading a component's code until it is first rendered |
| Loading interface |
Configured through the fallback prop |
Does not define a fallback itself |
| Usage |
Wraps content that may suspend |
Creates a lazy-loaded component |
| Used together |
Provides the loading boundary |
Provides the deferred component |
7. Using Suspense with Multiple Components
A single Suspense boundary can wrap several components. If any child suspends, React can replace the content within that boundary with its fallback until the required content is ready.
import { Suspense, lazy } from 'react';
const Profile = lazy(() => import('./Profile'));
const Notifications = lazy(() => import('./Notifications'));
function App() {
return (
<Suspense fallback={<p>Loading page content...</p>}>
<Profile />
<Notifications />
</Suspense>
);
}
export default App;
With one shared boundary, the profile and notifications area can appear together after all suspending content within that boundary is ready.
8. Nested Suspense Boundaries
Nested Suspense boundaries allow different parts of the page to have separate loading interfaces. This is useful when one section is ready before another.
import { Suspense, lazy } from 'react';
const Profile = lazy(() => import('./Profile'));
const Activity = lazy(() => import('./Activity'));
function App() {
return (
<Suspense fallback={<p>Loading page...</p>}>
<Profile />
<Suspense fallback={<p>Loading activity...</p>}>
<Activity />
</Suspense>
</Suspense>
);
}
export default App;
Explanation: The outer boundary handles the profile area and other content within it. The inner boundary provides a separate fallback for the activity section. React uses the closest Suspense boundary that can handle the suspended content.
9. Suspense with Conditional Rendering
You can conditionally render a lazy-loaded component and wrap it in Suspense. This is useful for previews, dialogs, settings panels, and optional page sections.
import { Suspense, lazy, useState } from 'react';
const Reports = lazy(() => import('./Reports'));
function App() {
const [showReports, setShowReports] = useState(false);
return (
<div>
<button onClick={() => setShowReports(!showReports)}>
{showReports ? 'Hide Reports' : 'Show Reports'}
</button>
{showReports && (
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
)}
</div>
);
}
export default App;
When the user selects Show Reports, React renders the component. If its code has not loaded yet, the fallback appears. After the component loads, the reports become visible.
10. Suspense and API Data Fetching
Suspense can also support data-loading patterns built for Suspense, such as reading supported promises with React's use() API or using a Suspense-enabled framework.
However, Suspense does not automatically detect every API request. For example, a request performed inside useEffect() does not trigger Suspense by itself.
Important distinction
- Supported Suspense data source: Can cause the nearest Suspense boundary to display its fallback.
- Ordinary fetch inside useEffect: Usually needs its own loading state, such as a state variable managed with
useState().
- Lazy-loaded component: Works with Suspense when its module code is still loading.
11. Example: Ordinary API Fetching with a Loading State
This example demonstrates a common API request using useEffect(). The loading message is controlled manually; wrapping this component in Suspense alone will not handle the request.
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Failed to load users');
}
return response.json();
})
.then(data => setUsers(data))
.catch(() => setError('Unable to load users.'))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading users...</p>;
if (error) return <p>{error}</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default Users;
This example illustrates manual loading-state management. It does not use Suspense for the API request.
12. Styling a Suspense Loading Indicator
You can style a fallback with CSS to make loading states more visually appealing.
function Loading() {
return <div className="loading-message">Loading, please wait...</div>;
}
.loading-message {
padding: 20px;
text-align: center;
font-size: 18px;
color: #333;
background: #f5f5f5;
border-radius: 8px;
}
Use a spinner or skeleton screen when it helps users understand which section is loading. Keep the fallback lightweight and consistent with the page layout.
13. Suspense Error Handling
Suspense handles suspended rendering, not every possible error. If a lazy-loaded module fails to download or an error occurs during rendering, use an Error Boundary to handle the failure and show an appropriate error message.
import { Component, Suspense, lazy } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <p>Something went wrong while loading this page.</p>;
}
return this.props.children;
}
}
function App() {
return (
<ErrorBoundary>
<Suspense fallback={<p>Loading dashboard...</p>}>
<Dashboard />
</Suspense>
</ErrorBoundary>
);
}
export default App;
Note: The Suspense fallback handles the waiting state, while the Error Boundary handles rendering errors that it catches. They serve different purposes.
14. Advantages of Suspense
- Provides a consistent approach to loading interfaces.
- Works naturally with React lazy loading.
- Allows separate loading states for different page sections.
- Can reduce the need to load all component code upfront.
- Supports progressive rendering patterns in Suspense-enabled frameworks.
- Helps developers coordinate when content is revealed to users.
15. Limitations and Common Mistakes
- Assuming every fetch triggers Suspense: Requests inside ordinary effects do not activate Suspense automatically.
- Forgetting the fallback: Always provide a suitable fallback for the intended loading boundary.
- Declaring lazy components inside another component: This can cause unexpected remounts and state resets.
- Using one boundary for every section: An overly broad boundary may hide content that could otherwise remain visible.
- Using an excessively large fallback: Keep loading UI simple and helpful.
- Ignoring errors: Add error handling for failures that Suspense does not handle.
- Overusing boundaries: Place boundaries according to the loading experience you want users to see.
16. Best Practices for Suspense
- Use meaningful fallback text, spinners, or skeleton components.
- Combine Suspense with
lazy() when splitting component code into separate chunks.
- Declare lazy components at the top level of the module.
- Use nested boundaries when sections should load independently.
- Choose boundary locations based on the intended user experience.
- Use Error Boundaries to handle relevant rendering failures.
- Do not expect Suspense to manage ordinary effect-based API requests automatically.
- Test loading, success, and error states.
17. Practical Project: Lazy-Loaded Product Details
Objective: Build a simple React page that loads a product details component when the user clicks a button.
ProductDetails.jsx
export default function ProductDetails() {
return (
<div>
<h2>Product Details</h2>
<p>Product: Wireless Headphones</p>
<p>Price: ₹1,999</p>
<p>Availability: In Stock</p>
</div>
);
}
App.jsx
import { Suspense, lazy, useState } from 'react';
const ProductDetails = lazy(() => import('./ProductDetails'));
function App() {
const [showProduct, setShowProduct] = useState(false);
return (
<main>
<h1>Online Store</h1>
<button onClick={() => setShowProduct(true)}>
View Product Details
</button>
{showProduct && (
<Suspense fallback={<p>Loading product details...</p>}>
<ProductDetails />
</Suspense>
)}
</main>
);
}
export default App;
Expected Result
- The page initially displays the Online Store heading and button.
- The product details component is not rendered until the button is clicked.
- While the component's code is loading, the fallback message can appear.
- After loading, the product details are displayed.
18. Interview Questions and Answers
Q1. What is Suspense in React?
Suspense is a built-in React component that displays a fallback UI while its children suspend during rendering.
Q2. What is the purpose of the fallback prop?
The fallback prop defines the UI React displays while the suspended content is not ready.
Q3. Can Suspense be used with lazy loading?
Yes. Suspense is commonly used with lazy() to display a loading interface while a component's code is being loaded.
Q4. Does Suspense automatically handle every API request?
No. It works with supported Suspense-enabled data sources. A request inside useEffect() does not automatically activate Suspense.
Q5. What is a nested Suspense boundary?
It is a Suspense boundary placed inside another boundary, allowing different parts of the interface to have different loading states.
Q6. What happens if a lazy-loaded component fails to load?
The loading promise can reject, so an Error Boundary can be used to display a suitable error interface.
Q7. Can the fallback contain JSX?
Yes. The fallback can contain text, JSX elements, a spinner component, or a skeleton layout.
Q8. Why should lazy components be declared outside component functions?
Declaring them at the top level helps prevent unexpected remounting and loss of component state.
19. Quick Revision Checklist
- Understand the purpose of Suspense.
- Know how to use the
fallback prop.
- Understand how Suspense works with
lazy().
- Practice shared and nested Suspense boundaries.
- Know the difference between loading states and error handling.
- Understand why ordinary
useEffect() fetching does not trigger Suspense automatically.
- Build a small project with a lazy-loaded component.
20. Learning Resources and Course Links
Conclusion
Suspense is an important React feature for managing loading interfaces when content suspends during rendering. It works especially well with lazy-loaded components and can coordinate how different sections of an application appear. Understanding fallback UI, nested boundaries, error handling, and the limits of Suspense will help you build more responsive and maintainable React applications.