A JavaScript error in a child component shouldn't take down your whole app. Error boundaries are special components that catch errors during rendering and show a fallback UI instead.
There's no hook equivalent yet — boundaries must be class components that implement at least one of:
static getDerivedStateFromError(error) — returns next state when a child throws
componentDidCatch(error, info) — for logging
class Boundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() {
if (this.state.hasError) return <p>Something went wrong</p>;
return this.props.children;
}
}
Your Task
Build an error boundary that protects a buggy button:
- Define class
ErrorBoundary with hasError state and getDerivedStateFromError
- When caught, render
<p id="error-fallback">Something went wrong</p>
- Otherwise, render
this.props.children
- Wrap the provided
<BuggyButton /> in <ErrorBoundary>