Error boundaries can help catch tricky errors that occur during the rendering phase. This error causes the app to unmount completely, and a blank page to appear.
This method catches JS errors, logs them, and then displays a fallback UI.
Error Boundaries make use of two methods that are already present in the React Components, as follows:
class ErrorBoundary extends Component {
state = {
error: null
}
static getDerivedStateFromError(error) {
// Update state so next render shows fallback UI.
return { error: error };
}
componentDidCatch(error, info) {
// Log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.error) {
// You can render any custom fallback UI
return <p>There has been an error</p>;
}
return this.props.children;
}
};
Note: Error boundaries only catch errors in the components below them in the tree, not within themselves.
This method works exactly like the catch{}
or the try/except
method in that it will propagate to the closest error boundary – the only difference is that it works only for the components.
Note: If an error is not caught by the error boundary, it will cause the whole component to unmount.
import React from 'react'; export default class BuggyCounter extends React.Component { constructor(props) { super(props); this.state = { counter: 1 }; this.handleClick = this.handleClick.bind(this); } //increment the counter handleClick() { this.setState(({counter}) => ({ counter: counter + 1 })); } render() { //throw error on 5 if (this.state.counter === 5) { throw new Error('Counter Crashed'); } return ( <div> <h2> {this.state.counter} </h2> <button onClick={this.handleClick}> + </button> </div> ); } }
RELATED TAGS
CONTRIBUTOR
View all Courses