React Suspense
Definition
`<Suspense>` lets you display a fallback UI (like a loading spinner) while you wait for some asynchronous operation (like fetching data or lazily loading a component) to finish.
Explain Like I'm New
Imagine waiting at a restaurant table for your food. Instead of leaving you staring at an empty plate (a blank white screen), the waiter brings you breadsticks (a Loading Spinner) to keep you happy until the real meal (the Data/Component) is ready. Suspense is the waiter automatically managing the breadsticks for you.
Real World Example
In traditional React, you have to write `if (loading) return <Spinner />` in every single component that fetches data. With Suspense, you just wrap the top of your app in `<Suspense fallback={<Spinner />}>`. Any component deep inside can pause to fetch data, and React automatically shows the spinner.
Common Use Cases
- •Code Splitting (React.lazy) to reduce initial bundle size
- •Data Fetching with Suspense-enabled frameworks (like Next.js or Relay)
- •Declarative loading states without boolean `isLoading` flags
Interactive Example
import React, { Suspense } from 'react'; // Lazily load a heavy component. // It won't be downloaded until it's actually rendered! const HeavyChart = React.lazy(() => import('./HeavyChart')); export default function Dashboard() { return ( <div> <h2>Welcome to your Dashboard</h2> {/* We MUST wrap lazy components in Suspense */} <Suspense fallback={<div>Loading massive chart...</div>}> <HeavyChart /> </Suspense> </div> ); }
Interview Questions
basic
- What is the `fallback` prop in `<Suspense>` used for?
- What is `React.lazy()`?
intermediate
- How does Suspense work with Error Boundaries?
- Does a standard `fetch()` or `axios` call automatically trigger Suspense?
advanced
- How does a component signal to Suspense that it is 'suspended' under the hood?
- How does Suspense behave differently in Concurrent React (React 18) compared to React 16?
trick
- If you nest multiple `<Suspense>` boundaries, which fallback is shown?