Sub topic 1
What Happens When a Component Throws While Rendering
Prerequisites
This chapter assumes you can write React function components and JSX. You should also know props, state, lifecycle methods, and basic throw and try/catch behavior.
When Rendering Throws
React renders a component by calling its function or lifecycle methods and building a UI tree. If a component throws an error during rendering, React cannot safely finish that part of the tree.
Without an error boundary, an uncaught rendering error causes React to unmount the whole application tree. The page may become blank, even if the error came from one small widget.
Error Boundaries: The Idea
An error boundary is a React class component that catches errors from its descendant tree. It can render fallback UI instead of allowing the error to remove the entire application.
A boundary catches errors thrown while rendering, in constructors, and in lifecycle methods of descendants. It does not automatically catch every JavaScript error. Its own implementation must also remain safe.
Writing a Class-Based Error Boundary
getDerivedStateFromError changes state before React renders again. componentDidCatch is the place to log the error and its component stack.
import { Component } from "react";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
console.error(error, info.componentStack);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}Wrap only the subtree that should be isolated:
function App() {
return (
<ErrorBoundary fallback={<p role="alert">Profile unavailable.</p>}>
<Profile />
</ErrorBoundary>
);
}If Profile throws while rendering, the boundary renders its fallback instead.
Showing a Useful Fallback
A fallback should tell users what failed and what they can do next. Use an accessible status such as role="alert". Avoid exposing stack traces or internal details. A later chapter will add retry and reset behavior.
Exercise
What happens when a descendant throws during rendering inside an error boundary?
Show answer
The boundary records the error, logs it through componentDidCatch, and renders its fallback instead of unmounting the whole app.