š 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)