Lesson 15 of 80
A render error in one component normally crashes the whole app — an error boundary is the one thing that can catch it and show a fallback instead, and it still requires a class component.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
Can you build an error boundary as a function component using hooks?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
By default, an uncaught error thrown during render anywhere in the tree unmounts the entire app — React deliberately doesn't leave a half-broken UI on screen. An error boundary is a component that catches render errors in its children and shows a fallback UI instead of taking down everything above it.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true }; // triggers the fallback render
}
componentDidCatch(error, info) {
logErrorToService(error, info); // side effect: reporting
}
render() {
if (this.state.hasError) return <h2>Something went wrong.</h2>;
return this.props.children;
}
}
<ErrorBoundary>
<WidgetThatMightThrow />
</ErrorBoundary>
ErrorBoundary wraps Widget. Normal rendering — children render straight through, untouched.
throw inside an onClick is a normal JS runtime error, not a render error — handle those with a regular try/catch inside the handler itself.setTimeout callback, a .then()) aren't caught either — same reason: they happen outside React's render call stack, where the boundary isn't watching."What does an error boundary catch, and what does it not catch?" is the real question — knowing the boundary exists is the easy part; knowing it's scoped to render-phase errors specifically (not events, not async) is what shows genuine hands-on understanding.