Professional React · Lesson 18 of 21
Suspense and error boundaries
Loading and errors at the tree level, and lazy-loading components.
10 minutes2 games
Instead of each component doing its own if (loading) and if (error), React offers a tree-level approach:
<Suspense fallback={…}>shows the fallback until everything inside finishes loading (alazycomponent, or data from a framework like Next.js).- An error boundary catches errors thrown while rendering its subtree and shows a fallback instead of a blank page.
React
// A component whose code "downloads" for a second (code splitting)
const Chart = React.lazy(() =>
new Promise((resolve) => setTimeout(() => resolve({ default: () => <p>📊 Chart loaded</p> }), 1000))
)
class ErrorBoundary extends React.Component {
state = { error: null }
static getDerivedStateFromError(error) {
return { error }
}
render() {
if (this.state.error) return <p style={{ color: "crimson" }}>Something broke: {this.state.error.message}</p>
return this.props.children
}
}
function Buggy() {
throw new Error("lesson data is missing")
}
function App() {
const [show, setShow] = useState(false)
return (
<div>
<Suspense fallback={<p>Loading chart…</p>}>
<Chart />
</Suspense>
<button onClick={() => setShow(true)}>Render a buggy component</button>
<ErrorBoundary>
{show && <Buggy />}
</ErrorBoundary>
<p>The rest of the page keeps working.</p>
</div>
)
}- <App>
- <Suspense fallback="Loading…">
- <Chart> (lazy)
- <ErrorBoundary>
- <Buggy> throws → boundary shows its fallback
- <p> unaffected
- <Suspense fallback="Loading…">
Quick question
A button inside an error boundary throws in its onClick. What happens?
Exercise
Wrap Profile in Suspense with the fallback Loading profile…. Profile is lazy, loads after 150 ms and shows Laila · 320 xp.
The page should show: Laila · 320 xp
React
const Profile = React.lazy(() =>
new Promise((resolve) => setTimeout(() => resolve({ default: () => <p>Laila · 320 xp</p> }), 150))
)
function App() {
return <div>Add Suspense here</div>
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.