Error BoundariesIntermediate
1Question 1 of 1
javascriptHow do Error Boundaries catch runtime errors in React component trees?
Explanation & Concept
Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole application.
Error boundaries must be implemented as class components using `static getDerivedStateFromError()` and `componentDidCatch()`.
Code Example
javascript
import React from "react";
export class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error("ErrorBoundary caught an error:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <div className="p-4 bg-red-50 text-red-700">Something went wrong.</div>;
}
return this.props.children;
}
}How It Works & Key Takeaways
Wrapping feature widgets in Error Boundaries ensures an unhandled runtime error in one widget does not blank out the entire page.
Mock Test · 1 Questions · Optional
Ready for Refs & forwardRef?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions