Suspense and React.lazy are tools for lazy loading components when they are actually needed.
Simple analogy: Imagine you are reading a book (website).
React.lazy — "Load when needed":
1const AdminPanel = React.lazy(() => import("./AdminPanel"));
The AdminPanel component will load only when it needs to be shown.
Suspense — show placeholder while loading:
1import { Suspense } from 'react';23function App() {4 return (5 <Suspense fallback={<Spinner />}>6 <AdminPanel />7 </Suspense>8 );9}
While the component is loading — Suspense shows fallback (Spinner).
Error handling with Suspense:
1import { Suspense, lazy } from "react";2import { ErrorBoundary } from "react-error-boundary";34const LazyComponent = lazy(() => import("./LazyComponent"));56function App() {7 return (8 <ErrorBoundary fallback={<p>Something went wrong</p>}>9 <Suspense fallback={<Spinner />}>10 <LazyComponent />11 </Suspense>12 </ErrorBoundary>13 );14}
Performance considerations:
What else Suspense can do (React 18+):