What are Error Boundaries ?
Definition: Error boundaries are components in React that catch JavaScript errors anywhere in their child component tree, log those errors, and display fallback UI instead of crashing the whole application. They are used to gracefully handle errors that occur during rendering, in lifecycle methods, and constructors of the whole component tree below them.
Features of Error Boundaries :
- Error boundaries work only in React applications.
- They catch errors during rendering, in lifecycle methods, and constructors of the whole component tree below them.
- They help prevent entire React applications from crashing due to errors in individual components.
- Error boundaries work asynchronously during rendering, so they don’t catch errors inside event handlers or asynchronous code.
- Error boundaries can be used to log errors and display fallback UI to the user.
Example:
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
class MyComponent extends Component {
render() {
return (
<ErrorBoundary>
<div>This is a component protected by ErrorBoundary.</div>
</ErrorBoundary>
);
}
}
export default MyComponent;
Output: If an error occurs within the ErrorBoundary, it will catch the error and display “Something went wrong.” Otherwise, it will render the component normally.
Difference between Error Boundaries & try-catch in React
“Error handling is an essential aspect of software development” to ensure that applications handle unexpected situations gracefully.” Error boundaries and try-catch are both mechanisms used in JavaScript for error handling, but they serve different purposes and use cases. Understanding when to use error boundaries and when to use try-catch is essential for effective error handling in your applications.
Both techniques catch and handle errors, but they differ in their application and use cases.
Table of Content
- Error Boundaries:
- Try-Catch:
- Difference between Error Boundaries & try-catch:
- When to Use which Approach: