Two production concerns: a single component throwing shouldn't blank the whole app, and you shouldn't ship every screen's code in one huge bundle. React answers with error boundaries and Suspense + lazy loading — both essential for real apps.
Error boundaries
An error boundary is a component that catches errors thrown by its children and renders a fallback instead of crashing. (They're still class components — one of the few things that must be.) In practice you use one from a library or write it once:
class ErrorBoundary extends React.Component {state = { hasError: false };static getDerivedStateFromError() { return { hasError: true }; }componentDidCatch(error, info) { logToService(error, info); }render() {if (this.state.hasError) return <p>Something went wrong.</p>;return this.props.children;}}<ErrorBoundary><Dashboard /></ErrorBoundary>
Lazy loading
React.lazy splits a component into its own bundle that only downloads when it's first rendered — faster initial loads:
const Dashboard = React.lazy(() => import("./Dashboard"));// Dashboard's code isn't downloaded until it renders.
Suspense
A lazily-loaded component "suspends" while its code downloads. <Suspense> shows a fallback (a spinner) during that wait:
<Suspense fallback={<Spinner />}><Dashboard /></Suspense>
Boundary granularity
Practice
Wrap a feature in an ErrorBoundary and deliberately throw inside a child to see the fallback. Lazy-load a heavy route with React.lazy and give it its own <Suspense fallback>. Confirm the chunk only downloads when you navigate to it.
Key takeaways
- 01Error boundaries catch errors from their children and render a fallback instead of crashing the app.
- 02They must be class components (getDerivedStateFromError + componentDidCatch) — write once or use a library.
- 03React.lazy code-splits a component so it downloads only when first rendered.
- 04Suspense shows a fallback while a lazy component loads.
- 05Give independent sections their own Suspense boundary so one slow chunk doesn't block the rest.
