Part 13 / Stage 3
Error boundaries and code-splitting
Goal: Know exactly what an error boundary catches - a render-phase throw in a descendant - and what it quietly does not: an event handler's throw, a rejected promise, anything outside render. Write the one class component this course still asks you to write, give it a real fallback and a working reset, then lazily load a part of the UI with
React.lazyandSuspenseand prove, for real, that its code only ships to the browser once something actually asks for it. Time: ~4 hours · Level: comfortable with components, state, and effects (Parts 1-11)
What you will learn
- Exactly what triggers
getDerivedStateFromError/componentDidCatch: a throw while React is building a descendant's JSX - nothing else - The three things a boundary does not catch - event handler throws, rejected promises/timers outside render, and its own crash - and the one real technique for getting an async error in front of a boundary anyway (catch it yourself, then re-throw it during the next render)
- Writing the class-based boundary itself: why it is still a class in React 19.3.1 specifically (checked against this repo's own installed React, not assumed),
getDerivedStateFromErrorvscomponentDidCatch, and a fallback as a function so it can read the real error and offer a working retry - Three reset patterns and when each one is the right one: a retry button that fixes the underlying cause before resetting,
resetKeysfor "the thing I'm watching changed, forget the old error with no button at all," and remounting with a changedkeywhen starting the whole subtree over is simplest React.lazy(() => import(...))+<Suspense fallback={...}>for code-splitting a part of the UI that most sessions never need- How to actually prove a lazy chunk loads on demand, not just hope it does: at the test level, by spying on the import itself, and with one real
vite buildshowing two separate files indist/
A note on how this part is organised: same convention as every earlier part - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below.
Topics in this part
Practice
Every exercise below is a real .jsx component (or a Broken/Fixed pair), paired with a .test.jsx that actually renders it with Testing Library/Vitest - the same verified-output rule as every example in this course. Any exercise that renders a deliberate crash silences React's own console.error logging the same way this part's examples do (vi.spyOn(console, "error").mockImplementation(() => {})).
Exercise 1: A first boundary - a delivery estimate that must not blank the screen
Scenario: A Swiggy-style delivery estimate widget is handed etaMinutes straight from an upstream service that occasionally sends null instead of a number, and the arithmetic on it throws.
What to do: Write DeliveryEtaWidget({ etaMinutes }) (throws while rendering if etaMinutes is not a number - e.g. etaMinutes.toFixed(0) on null), a class ErrorBoundary with getDerivedStateFromError/componentDidCatch and a fallback function prop (same shape as examples/02_class_error_boundary_with_fallback.jsx), and CrashProofEta wiring them together with a fallback showing the error's message.
Sample output (really run):
etaMinutes: 18 -> "Arriving in 18 min"
etaMinutes: null -> role="alert": "Could not show the ETA: <message>"
💡 Hint: this is examples/02_class_error_boundary_with_fallback.jsx's exact shape, renamed - a component that throws mid-render on bad data, a reusable class boundary, and a fallback function that reads the real error.
Exercise 2: What a boundary does not see - a wishlist button
Scenario: A "Remove from wishlist" button occasionally throws inside its own click handler (a bug in a teammate's analytics call, say) - and whoever wrote it assumed wrapping the button in an error boundary would protect against that too.
What to do: Write removeFromWishlist() (a plain function that throws "wishlist service unreachable"), RemoveFromWishlistButton using it as an onClick, and a boundary wrapped around it. Prove, the same way examples/01_render_vs_event_vs_async_errors.test.jsx does, that calling removeFromWishlist() directly throws a plain exception, and that rendering the button inside the boundary shows no fallback at all (nothing threw during render).
Sample output (really run):
removeFromWishlist() called directly -> throws "wishlist service unreachable"
<ErrorBoundary><RemoveFromWishlistButton /></ErrorBoundary> rendered -> button shown, no alert anywhere
💡 Hint: this part's Section 1 names the rule directly - a boundary only watches render, and a click happens nowhere near it.
Exercise 3: Find and fix a retry that does not fix anything
Scenario: A teammate added a "Try again" button to a cart-item boundary, but a reviewer points out it just makes the error reappear immediately:
function CartItemBroken({ item }) {
if (item.quantity > item.stock) {
throw new Error(`only ${item.stock} left of ${item.name}, cannot keep quantity ${item.quantity}`);
}
return <p>{item.name} x{item.quantity}</p>;
}
// Inside the boundary's fallback:
<button onClick={reset}>Try again</button>
Clicking "Try again" resets the boundary, and CartItemBroken renders with the exact same over-stocked item it had before - so it throws again on the spot.
What to do: Write CartItemBroken (the code above, unchanged) and CartItemFixedRetry, whose retry button first caps quantity down to stock and then calls reset() - the same order examples/03_reset_pattern_retry_and_key_remount.jsx's RetryFixesCauseFirst uses.
Sample output (really run, item quantity 5, stock 2):
CartItemBroken + "Try again": alert reappears immediately, same message
CartItemFixedRetry + "Try again": "Fresh Produce Co x2" - quantity capped, no alert
💡 Hint: this is this part's Section 2/3 gotcha exactly - resetting a boundary only forgets its own state, never whatever actually caused the throw.
Exercise 4: resetKeys - clearing a stale error when the selection changes
Scenario: A product detail page shows one product at a time. If the selected product is out of stock, a boundary shows an error - but switching to a different product should never still be showing yesterday's error, and nobody should need to click anything for that to happen.
What to do: Write ProductDetail({ product }) (throws if product.stock === 0), a boundary with the resetKeys comparison from examples/03_reset_pattern_retry_and_key_remount.jsx's componentDidUpdate, and ProductBrowser - a "Next product" button outside the boundary, cycling through at least one out-of-stock product and one in-stock one, with resetKeys={[product.id]}.
Sample output (really run, starting on the out-of-stock product):
initial: role="alert": "Could not show this product: ..."
click "Next product": "Wireless Mouse - ₹799" - no alert, nothing inside the boundary was clicked
💡 Hint: this is examples/03_reset_pattern_retry_and_key_remount.jsx's AutoResetOnOrderChange shape, renamed - the boundary resets itself the moment its resetKeys entry changes.
Exercise 5: Lazy-load a reviews panel, and prove it is actually lazy
Scenario: A product page's "Reviews" section is long, rarely opened, and has no reason to ship in the page's first bundle.
What to do: Write a ReviewsPanel component in its own file (plain, nothing React.lazy-specific about it - the same shape as examples/04_lazy_settings_panel.jsx), and a ReviewsPanelLauncher in a second file using lazy(() => import(...)) and Suspense behind an "Show reviews"/"Hide reviews" toggle button, the same shape as examples/05_lazy_and_suspense_settings_panel.jsx. In the test, use vi.hoisted + vi.mock to spy on the import the same way, and prove: zero calls while closed, exactly one call after opening, and still exactly one call after closing and reopening.
Sample output (really run):
closed: importSpy called 0 times
opened: "Loading reviews..." then the real panel - importSpy called 1 time
closed, opened again: the real panel again immediately - importSpy still called 1 time
💡 Hint: this is this part's Section 4/5 pattern end to end, on a new domain - don't call the import yourself anywhere in the test file outside the mock factory, or you will load the module before the component ever does.
Exercise 6: A lazy load that fails, caught by a boundary
Scenario: A "Checkout" module is lazily loaded, and - like any network request - its chunk can fail to load (a flaky connection, a stale deploy whose old chunk URL 404s). A failed lazy load should look like "something went wrong, try again," never a blank white screen.
What to do: Write CheckoutLauncher, wrapping a lazy(() => import("./some-checkout-module")) component in both a Suspense (fallback: "Loading checkout...") and a wrapping ErrorBoundary (fallback: an alert naming the failure). In the test, use lazy(() => Promise.reject(new Error("checkout module failed to load"))) directly (no real module needed - the point is the rejection, not the content) to simulate a chunk that 404s, and prove the boundary's fallback appears - not a crash, not a stuck "Loading checkout..." forever.
Sample output (really run):
first paint: "Loading checkout..."
settled: role="alert": "Could not load checkout: checkout module failed to load"
💡 Hint: a rejected dynamic import is still just a throw that happens while Suspense is trying to resolve what to render - which makes it exactly the kind of render-phase error Section 1 and Section 2 already covered; Suspense and ErrorBoundary are not in competition here, they are both needed, one above the other.
Show the solutions for Part 13 (15 files)
solutions/ex01_delivery_eta_crash_proof.jsx
import { Component } from "react";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
resetBoundary = () => {
this.setState({ error: null });
};
render() {
if (this.state.error) return this.props.fallback(this.state.error, this.resetBoundary);
return this.props.children;
}
}
// Throws mid-render when the upstream service sends something that is not
// a number - `null.toFixed` does not exist, so this throws before any JSX
// is even built, exactly the "render error" shape Section 1 describes.
export function DeliveryEtaWidget({ etaMinutes }) {
return <p>Arriving in {etaMinutes.toFixed(0)} min</p>;
}
export function CrashProofEta({ etaMinutes }) {
return (
<ErrorBoundary
fallback={(error, reset) => (
<div role="alert">
<p>Could not show the ETA: {error.message}</p>
<button onClick={reset}>Try again</button>
</div>
)}
>
<DeliveryEtaWidget etaMinutes={etaMinutes} />
</ErrorBoundary>
);
}
solutions/ex01_delivery_eta_crash_proof.test.jsx
import { describe, test, expect, vi, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import { CrashProofEta } from "./ex01_delivery_eta_crash_proof.jsx";
afterEach(() => {
vi.restoreAllMocks();
});
describe("CrashProofEta", () => {
test("a numeric eta renders plainly, with no fallback anywhere", () => {
render(<CrashProofEta etaMinutes={18} />);
expect(screen.getByText("Arriving in 18 min")).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
test("a missing eta throws mid-render, and the boundary's fallback replaces it instead of a blank screen", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
render(<CrashProofEta etaMinutes={null} />);
expect(screen.getByRole("alert")).toHaveTextContent(
"Could not show the ETA: Cannot read properties of null (reading 'toFixed')"
);
expect(screen.getByRole("button", { name: "Try again" })).toBeInTheDocument();
});
});
solutions/ex02_wishlist_button_not_caught.jsx
import { Component } from "react";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) return <p role="alert">Could not remove this item</p>;
return this.props.children;
}
}
// A plain function, pulled out on its own so a test can call it directly
// with no DOM in the way - the whole point of this exercise is that this
// throw has nothing to do with rendering at all.
export function removeFromWishlist() {
throw new Error("wishlist service unreachable");
}
export function RemoveFromWishlistButton() {
return <button onClick={removeFromWishlist}>Remove from wishlist</button>;
}
solutions/ex02_wishlist_button_not_caught.test.jsx
import { describe, test, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { ErrorBoundary, removeFromWishlist, RemoveFromWishlistButton } from "./ex02_wishlist_button_not_caught.jsx";
describe("what the boundary never sees", () => {
test("calling the handler directly throws a plain exception - nothing boundary-specific about it", () => {
expect(() => removeFromWishlist()).toThrow("wishlist service unreachable");
});
test("rendering the button inside a boundary shows no fallback - nothing threw during render", () => {
render(
<ErrorBoundary>
<RemoveFromWishlistButton />
</ErrorBoundary>
);
expect(screen.getByRole("button", { name: "Remove from wishlist" })).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
solutions/ex03_cart_item_retry_fixes_cause.jsx
import { Component, useState } from "react";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
resetBoundary = () => {
this.setState({ error: null });
};
render() {
if (this.state.error) return this.props.fallback(this.state.error, this.resetBoundary);
return this.props.children;
}
}
function CartItem({ item }) {
if (item.quantity > item.stock) {
throw new Error(`only ${item.stock} left of ${item.name}, cannot keep quantity ${item.quantity}`);
}
return (
<p>
{item.name} x{item.quantity}
</p>
);
}
// BROKEN: the retry button only resets the boundary - the exact same
// over-stocked `item` renders again immediately and throws again.
export function CartItemBroken() {
const item = { name: "Fresh Produce Co", quantity: 5, stock: 2 };
return (
<ErrorBoundary
fallback={(error, reset) => (
<div role="alert">
<p>{error.message}</p>
<button onClick={reset}>Try again</button>
</div>
)}
>
<CartItem item={item} />
</ErrorBoundary>
);
}
// FIXED: the retry caps quantity down to stock FIRST, and only then
// resets - so the next render has something that will not throw.
export function CartItemFixedRetry() {
const [item, setItem] = useState({ name: "Fresh Produce Co", quantity: 5, stock: 2 });
function retryWithCappedQuantity(reset) {
setItem((current) => ({ ...current, quantity: current.stock }));
reset();
}
return (
<ErrorBoundary
fallback={(error, reset) => (
<div role="alert">
<p>{error.message}</p>
<button onClick={() => retryWithCappedQuantity(reset)}>Try again</button>
</div>
)}
>
<CartItem item={item} />
</ErrorBoundary>
);
}
solutions/ex03_cart_item_retry_fixes_cause.test.jsx
import { describe, test, expect, vi, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { CartItemBroken, CartItemFixedRetry } from "./ex03_cart_item_retry_fixes_cause.jsx";
afterEach(() => {
vi.restoreAllMocks();
});
describe("CartItemBroken", () => {
test("Try again re-crashes immediately - the same over-stocked item is still there", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const user = userEvent.setup();
render(<CartItemBroken />);
expect(screen.getByRole("alert")).toHaveTextContent("only 2 left of Fresh Produce Co");
await user.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.getByRole("alert")).toHaveTextContent("only 2 left of Fresh Produce Co");
});
});
describe("CartItemFixedRetry", () => {
test("Try again caps the quantity first, then actually recovers", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const user = userEvent.setup();
render(<CartItemFixedRetry />);
expect(screen.getByRole("alert")).toHaveTextContent("only 2 left of Fresh Produce Co");
await user.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByText("Fresh Produce Co x2")).toBeInTheDocument();
});
});
solutions/ex04_product_detail_reset_keys.jsx
import { Component, useState } from "react";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidUpdate(prevProps) {
if (this.state.error && prevProps.resetKeys?.some((key, i) => key !== this.props.resetKeys[i])) {
this.setState({ error: null });
}
}
render() {
if (this.state.error) return <p role="alert">Could not show this product: {this.state.error.message}</p>;
return this.props.children;
}
}
function ProductDetail({ product }) {
if (product.stock === 0) {
throw new Error(`${product.name} is out of stock and has no detail page right now`);
}
return (
<p>
{product.name} - ₹{product.price}
</p>
);
}
const PRODUCTS = [
{ id: "P-1", name: "Bluetooth Speaker", price: 1999, stock: 0 },
{ id: "P-2", name: "Wireless Mouse", price: 799, stock: 14 },
];
export function ProductBrowser() {
const [index, setIndex] = useState(0);
const product = PRODUCTS[index];
return (
<div>
<button onClick={() => setIndex((i) => (i + 1) % PRODUCTS.length)}>Next product</button>
<ErrorBoundary resetKeys={[product.id]}>
<ProductDetail product={product} />
</ErrorBoundary>
</div>
);
}
solutions/ex04_product_detail_reset_keys.test.jsx
import { describe, test, expect, vi, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ProductBrowser } from "./ex04_product_detail_reset_keys.jsx";
afterEach(() => {
vi.restoreAllMocks();
});
describe("ProductBrowser", () => {
test("the out-of-stock product starts out crashed, and switching products clears it with no button inside the boundary", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const user = userEvent.setup();
render(<ProductBrowser />);
expect(screen.getByRole("alert")).toHaveTextContent("Bluetooth Speaker is out of stock");
await user.click(screen.getByRole("button", { name: "Next product" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByText("Wireless Mouse - ₹799")).toBeInTheDocument();
});
});
solutions/ex05_reviews_panel_launcher.jsx
import { lazy, Suspense, useState } from "react";
const ReviewsPanel = lazy(() => import("./ex05_reviews_panel.jsx"));
export function ReviewsPanelLauncher({ productName }) {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen((isOpen) => !isOpen)}>{open ? "Hide reviews" : "Show reviews"}</button>
{open && (
<Suspense fallback={<p>Loading reviews...</p>}>
<ReviewsPanel productName={productName} />
</Suspense>
)}
</div>
);
}
solutions/ex05_reviews_panel_launcher.test.jsx
import { describe, test, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const { importSpy } = vi.hoisted(() => ({ importSpy: vi.fn() }));
vi.mock("./ex05_reviews_panel.jsx", async () => {
importSpy();
return vi.importActual("./ex05_reviews_panel.jsx");
});
const { ReviewsPanelLauncher } = await import("./ex05_reviews_panel_launcher.jsx");
describe("ReviewsPanelLauncher", () => {
test("stays closed until asked - the chunk is never requested up front", () => {
render(<ReviewsPanelLauncher productName="Bluetooth Speaker" />);
expect(screen.getByRole("button", { name: "Show reviews" })).toBeInTheDocument();
expect(importSpy).not.toHaveBeenCalled();
});
test("opening it loads the chunk exactly once, even across a close/reopen", async () => {
const user = userEvent.setup();
render(<ReviewsPanelLauncher productName="Bluetooth Speaker" />);
await user.click(screen.getByRole("button", { name: "Show reviews" }));
expect(importSpy).toHaveBeenCalledTimes(1);
expect(await screen.findByText("No reviews yet for Bluetooth Speaker")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Hide reviews" }));
await user.click(screen.getByRole("button", { name: "Show reviews" }));
expect(await screen.findByText("No reviews yet for Bluetooth Speaker")).toBeInTheDocument();
expect(importSpy).toHaveBeenCalledTimes(1);
});
});
solutions/ex05_reviews_panel.jsx
// The component React.lazy() loads - kept in its own file for the same
// reason examples/04_lazy_settings_panel.jsx is: import() splits at file
// boundaries. `loadCount` exists purely so a test can prove the module's
// body ran exactly once.
export let loadCount = 0;
loadCount += 1;
export default function ReviewsPanel({ productName }) {
return (
<section>
<h2>Reviews</h2>
<p>No reviews yet for {productName}</p>
</section>
);
}
solutions/ex05_reviews_panel.test.jsx
import { describe, test, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import ReviewsPanel, { loadCount } from "./ex05_reviews_panel.jsx";
describe("ReviewsPanel", () => {
test("renders plainly on its own", () => {
render(<ReviewsPanel productName="Bluetooth Speaker" />);
expect(screen.getByRole("heading", { name: "Reviews" })).toBeInTheDocument();
expect(screen.getByText("No reviews yet for Bluetooth Speaker")).toBeInTheDocument();
});
test("the module body ran exactly once", () => {
expect(loadCount).toBe(1);
});
});
solutions/ex06_checkout_form.jsx
// The real module CheckoutLauncher lazily loads, in its own file for the
// same file-boundary reason as every other lazy target in this part.
export default function CheckoutForm() {
return <p>Checkout form ready</p>;
}
solutions/ex06_checkout_lazy_load_failure.jsx
import { Component, Suspense, lazy } from "react";
// Exported so the paired test can reuse this exact boundary around a
// *different*, deliberately-failing lazy component, to prove the
// Suspense+ErrorBoundary pairing handles a failed chunk, not just the
// normal success path CheckoutLauncher shows below.
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) return <p role="alert">Could not load checkout: {this.state.error.message}</p>;
return this.props.children;
}
}
const Checkout = lazy(() => import("./ex06_checkout_form.jsx"));
export function CheckoutLauncher() {
return (
<ErrorBoundary>
<Suspense fallback={<p>Loading checkout...</p>}>
<Checkout />
</Suspense>
</ErrorBoundary>
);
}
solutions/ex06_checkout_lazy_load_failure.test.jsx
import { describe, test, expect, vi, afterEach } from "vitest";
import { Suspense, lazy } from "react";
import { render, screen } from "@testing-library/react";
import { ErrorBoundary, CheckoutLauncher } from "./ex06_checkout_lazy_load_failure.jsx";
afterEach(() => {
vi.restoreAllMocks();
});
describe("CheckoutLauncher: the normal, successful lazy load", () => {
test("shows a fallback first, then the real checkout module", async () => {
render(<CheckoutLauncher />);
expect(await screen.findByText("Checkout form ready")).toBeInTheDocument();
});
});
describe("the same boundary, around a chunk that fails to load", () => {
test("a rejected dynamic import is caught by the wrapping boundary - not a blank screen, not a stuck fallback", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
// No real second module needed: a lazy component whose loader rejects
// behaves exactly like a chunk that 404s once the network fails.
const BrokenCheckout = lazy(() => Promise.reject(new Error("checkout module failed to load")));
render(
<ErrorBoundary>
<Suspense fallback={<p>Loading checkout...</p>}>
<BrokenCheckout />
</Suspense>
</ErrorBoundary>
);
expect(screen.getByText("Loading checkout...")).toBeInTheDocument();
expect(await screen.findByRole("alert")).toHaveTextContent(
"Could not load checkout: checkout module failed to load"
);
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Assuming a try/catch around an event handler call, or a .catch() on a stray promise, is what an error boundary is for |
Boundaries only watch for throws during React's render phase - an event handler's throw and a rejected promise both happen outside render, on their own call stack or microtask, and a boundary never sees either one | Use plain try/catch for handlers and .catch() for promises, as this course already teaches; reach for a boundary specifically for render-phase failures (Section 1) |
| Wanting a boundary to cover an async failure, and assuming there is no way to make that happen | It is true that a rejection by itself never reaches a boundary - but that does not mean the error has to stay invisible to one | Catch the async error, store it in state, and throw it during the component's own render on the next pass (examples/01...jsx's PlaceOrderAsyncSurfaced, Section 1) |
Writing an error boundary as a function component, assuming React 19's newer hooks (use, useActionState) cover this too |
getDerivedStateFromError/componentDidCatch are still lifecycle methods only a class instance has, confirmed directly against this course's own installed React 19.3.1 - no hook equivalent exists |
Write the one class this course asks for (Section 2); everything else in this course stays function components and hooks |
| A retry button that only calls the boundary's own reset, with nothing fixing whatever actually threw | The boundary forgot its own error state, but the data that caused the throw is exactly as bad as it was - the very next render throws again immediately | Fix the underlying cause first, then reset (Section 3's Pattern 1) - or use resetKeys/a changed key when there is nothing a button needs to fix (Patterns 2-3) |
Calling React.lazy(import("./Panel.jsx")) instead of React.lazy(() => import("./Panel.jsx")) |
Without the arrow function, the dynamic import starts immediately, at module-evaluation time - defeating the entire point of splitting it out, and leaving React with no way to retry a failed load | Always wrap it in a function; let React.lazy decide when to call it (Section 4) |
Trusting that lazy/Suspense code-splits just because the syntax looks right, without ever checking |
A typo in the import path, a bundler config that inlines everything anyway, or a plugin that breaks splitting silently produces one giant bundle with nothing actually deferred | Verify it two ways: a test that spies on the import to prove when it runs, and one real production build showing two separate files in dist/ (Section 5) |
Quick recap
- An error boundary catches exactly one thing: a throw while React is rendering a descendant - not an event handler's throw, not a rejected promise, not anything outside render.
- The real way to let a boundary see an async or event-handler-shaped error anyway: catch it yourself, store it, and throw it back out during the component's own next render.
getDerivedStateFromError(render-phase, pure, returns fallback state) andcomponentDidCatch(commit-phase, once per error, gets the component stack) are still the only way to write a boundary in React 19.3.1 - the one class this course still asks you to write, confirmed directly against this repo's own installed React rather than assumed.- A reset button has to fix whatever actually caused the throw before it resets, or the very next render throws again;
resetKeysand a changedkeycover the "nothing a button needs to fix, just forget the old error" cases. React.lazy(() => import(...))+<Suspense fallback={...}>split a part of the UI into its own chunk, downloaded only once something actually needs it, and cached forever after that.- "It's lazy" is worth proving, not assuming: spy on the import to prove when it runs, and check a real
vite build'sdist/output for two separate files, not one.
Checklist
- I can say, in one sentence, exactly what triggers an error boundary (a throw during React's render of a descendant) and name the two ordinary kinds of errors it never sees.
- I reproduced Section 1's async fix myself - caught a rejection in state, then threw it during the next render, and watched a boundary catch it that could not catch the bare rejection.
- I wrote (or re-typed) a class-based
ErrorBoundarywithgetDerivedStateFromErrorandcomponentDidCatch, and can explain why there is still no hook version in this repo's installed React. - I proved, with a real click, that resetting a boundary alone re-crashes on still-bad data - then fixed it with a retry that updates the data first.
- I built a
resetKeys-style auto-reset and akey-remount reset, and can say in one sentence when each is the right choice over a retry button. - I lazily loaded a component with
React.lazy/Suspense, watched its fallback show first, and proved with a spy that opening it loads the chunk exactly once, no matter how many times it is reopened.