π Error Boundaries in React β Catch JavaScript Errors Without Crashing the Whole App
Error boundaries are React components that catch JavaScript errors in child components, log them, and show a fallback UI instead of crashing the entire app.
π― Why use error boundaries?
β’ Prevent UI from breaking due to unexpected errors
β’ Provide a graceful fallback (like an error message)
β’ Great for critical areas like routes, forms, dashboards
β οΈ Only class components can be error boundaries (as of now).
π§± Example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
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;
}
}
β
Usage:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
π Key points:
β’ Catches errors during rendering, lifecycle, and constructors
β’ Does not catch event handler errors (handle them manually)
β’ Useful for isolating risky parts of the app
Error boundaries improve the resilience of your React app and ensure a better user experience even when something fails.
Top comments (0)