Error Boundaries are class components that catch rendering errors and show a fallback UI instead of crashing the app. Define getDerivedStateFromError() to update state on error. Use react-error-boundary for a simpler API.
Error Boundaries
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
render() {
if (this.state.hasError) {
return Something went wrong: {this.state.error?.message}
;
}
return this.props.children;
}
}
// Usage