What Is Suspense in React: Simple Explanation and Example
Suspense is a component that lets you show a fallback UI (like a loading spinner) while waiting for some code or data to load. It helps manage asynchronous loading smoothly by pausing rendering until the needed content is ready.How It Works
Imagine you are waiting for a friend to bring a book before you can start reading together. Instead of staring at an empty table, you put a placeholder like a "Waiting for book..." sign. Suspense works similarly in React. It lets you show a temporary UI while some part of your app is still loading.
When React encounters a component wrapped in Suspense that is not ready (like a component loading data or code), it pauses rendering that part and shows the fallback UI you provide. Once the content is ready, React replaces the fallback with the actual content automatically.
This makes your app feel smoother and more user-friendly because users see a clear loading state instead of a blank screen or broken content.
Example
This example shows how to use Suspense with a lazy-loaded component. While the component loads, a loading message appears.
import React, { Suspense, lazy } from 'react'; const LazyComponent = lazy(() => new Promise(resolve => { setTimeout(() => { resolve({ default: () => <div>Loaded Component Content</div> }); }, 2000); })); export default function App() { return ( <div> <h1>My App</h1> <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> </div> ); }
When to Use
Use Suspense when you want to handle loading states for components that load asynchronously. This includes:
- Lazy loading components to split your app into smaller chunks and improve performance.
- Waiting for data fetching libraries that support Suspense to load data before showing UI.
- Showing fallback UI like spinners or messages while waiting for images, code, or data.
It is especially useful in large apps where loading everything at once would slow down the user experience.
Key Points
- Suspense lets you show fallback UI while waiting for async content.
- It works well with lazy-loaded components and data fetching.
- Improves user experience by avoiding blank or broken screens.
- Requires React 16.6 or newer for lazy loading support.
- Helps split app code for faster initial loading.