Use a fallback UI to handle errors gracefully.?
Example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true }; // Update state to trigger a fallback
UI
}
componentDidCatch(error, info) {
console.error("Error caught by Error Boundary:", error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong!</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
You can wrap parts of your app in this ErrorBoundary to gracefully handle errors.