5 questions foundWhat is an error boundary in React and why is it useful?
Beginner An error boundary is a special component that catches JavaScript errors happening anywhere in its child components, and shows a friendly fallback message instead of letting the entire app crash and show a blank white screen to the user.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) return <p>Something went wrong, please try again</p>;
return this.props.children;
}
}
<ErrorBoundary>
<ProductList />
</ErrorBoundary>
Real-world example An online store wraps its product list in an error boundary, so if one product's data is broken and causes an error, the customer sees a friendly message instead of the whole website going completely blank.
Common follow-ups: What kinds of errors does an error boundary fail to catch, such as errors inside event handlers?;Can you nest multiple error boundaries in different parts of an app?
Class Components & Legacy Lifecycle Methods;Testing
How do you log error details when an error boundary catches an error?
Intermediate You add the componentDidCatch method to your error boundary class, which receives the actual error object and information about where it happened. This is a good place to send the error details to a logging service so your team can find and fix the problem later.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info.componentStack);
}
render() {
if (this.state.hasError) return <p>Something went wrong</p>;
return this.props.children;
}
}
Real-world example A team's error boundary automatically sends every caught error, along with which component it happened in, to their monitoring service, so they find out about real user problems before customers even need to report them.
Common follow-ups: What information does componentStack actually tell you about where the error happened?;How would you also show a button letting the user try reloading the broken section?
React DevTools & Debugging;Testing
Why does React not catch errors that happen inside event handlers, like an onClick function, using error boundaries?
Intermediate Error boundaries only catch errors that happen while React is rendering, updating lifecycle methods, or during construction. An error thrown inside an event handler happens outside of that rendering process, so it does not crash the component tree the same way, and needs to be handled with a regular try catch block instead.
function DeleteButton({ id }) {
function handleClick() {
try {
deleteItem(id);
} catch (error) {
console.error('Failed to delete item', error);
alert('Something went wrong while deleting');
}
}
return <button onClick={handleClick}>Delete</button>;
}
Real-world example A delete button wraps its click handler logic in a regular try catch block, since an error boundary placed around the button would not actually catch an error thrown directly inside that click function.
Common follow-ups: What other kinds of errors, besides event handler errors, do error boundaries fail to catch?;How would you handle an error that happens inside an asynchronous function called from an event handler?
Error Handling;Effects & Lifecycle
How would you build a reusable error boundary that lets the user retry after an error occurs?
Advanced You add a button inside the fallback view that resets the error boundary's state back to no error, allowing React to attempt rendering the children again from scratch. This gives users a way to recover from a temporary problem without needing to reload the entire page.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
handleRetry = () => this.setState({ hasError: false });
render() {
if (this.state.hasError) {
return (
<div>
<p>Something went wrong</p>
<button onClick={this.handleRetry}>Try Again</button>
</div>
);
}
return this.props.children;
}
}
Real-world example A dashboard widget that occasionally fails due to a slow network request gives the user a Try Again button, letting them retry loading just that one widget instead of needing to refresh the entire page.
Common follow-ups: What happens if the same underlying problem causes the error again right after clicking retry?;How would you add a maximum number of retry attempts before showing a different message?
Design Patterns in React;Custom Hooks
Where should you place error boundaries in a real React app?
Beginner A good approach is placing one error boundary around your entire app as a safety net, and then placing smaller, more specific error boundaries around individual features or sections. This way, if one small part of the page breaks, the rest of the app keeps working normally instead of the whole page going blank.
<ErrorBoundary>
<Header />
<ErrorBoundary>
<ProductRecommendations />
</ErrorBoundary>
<MainContent />
</ErrorBoundary>
Real-world example A news website wraps its unreliable third party advertisement widget in its own small error boundary, so if the ad script fails, only that specific ad space shows a fallback message while the actual news article keeps displaying normally.
Common follow-ups: How many error boundaries is too many for a typical page?;Should every single component have its own dedicated error boundary?
Component Composition & Children Props;Testing