Create an Error Boundary component in React
Catch runtime errors in React components using class-based Error Boundaries.
Advertisement
Question
Create an Error Boundary component in React.
Answer
Error Boundaries catch runtime errors during rendering or lifecycle methods, preventing the entire app from crashing.
They must be class components because they use lifecycle methods like componentDidCatch.
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error('Error caught:', error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong!</h2>;
}
return this.props.children;
}
}
export default function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}
âś… Wrap critical UI sections in ErrorBoundary components for safety.
Real-World Example
- Catching crashes in dashboards or widgets
- Wrapping risky components like charts, APIs, or 3rd-party integrations
Quick Practice
Create an ErrorBoundary that logs errors to a custom analytics endpoint.
Summary
Use class-based Error Boundaries to prevent the entire React tree from crashing due to child errors.
Do Error Boundaries work in functional components?
Not directly. You can wrap logic in a class or use libraries like react-error-boundary.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement