How do you handle errors in React applications?
Handling errors in React is done using Error Boundaries. They are React components
that catch JavaScript errors anywhere in their child component tree and log those errors or
display a fallback UI.
Example of Error Boundary:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true }; // Update state to trigger fallback
UI
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong!</h1>;
}
return this.props.children;
}
}
You wrap your components inside ErrorBoundary to catch and handle errors gracefully.