An Error Boundary in React is a special type of component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the whole app .
setTimeout
, Promises)
class ErrorBoundary extends React.Component {
You're defining a class component named ErrorBoundary
. It extends React.Component
, meaning it inherits lifecycle methods like render
, componentDidCatch
, etc.
This component will act as a boundary to catch JavaScript errors in its child components.
constructor(props) {
super(props);
this.state = { hasError: false };
}
constructor
: Called when the component is created.super(props)
: Calls the parent class constructor with props, required when using this.props
.this.state
: Initializes a state variable hasError
to track whether an error occurred.
static getDerivedStateFromError(error) {
return { hasError: true };
}