This tutorial aims to provide a detailed understanding of Error Boundaries and Fallbacks in React. These concepts are vital for resilient app development as they provide a fallback UI when a component throws an error.
By the end of the tutorial, you should be able to:
- Understand what Error Boundaries and Fallbacks are
- Implement Error Boundaries and Fallbacks in a React app
- Handle errors gracefully in your application
You should have a basic understanding of React and JavaScript before diving into this tutorial.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
To create an Error Boundary, you need to have a class component that uses either (or both) of the lifecycle methods getDerivedStateFromError
or componentDidCatch
.
getDerivedStateFromError
: This lifecycle method works like a catch JavaScript block. It’s called during the “render” phase, so side-effects are not permitted.
componentDidCatch
: This lifecycle method works like a catch JavaScript block, but it’s called during the “commit” phase, so side-effects are allowed.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
In the above code snippet, if an error is thrown in a part of the UI inside the ErrorBoundary
, the error boundary will catch the error, log it, and then display the fallback UI.
In this tutorial, you learned about Error Boundaries and Fallbacks in React. You learned how to create a class component that uses the lifecycle methods getDerivedStateFromError
or componentDidCatch
to create an error boundary. You also learned how to render a fallback UI when an error is caught.
Create a simple React component that throws an error, then wrap it with an error boundary to catch the error and display a fallback UI.
Improve your error boundary by adding an error reporting service in the componentDidCatch
lifecycle method.
Create an error boundary that shows a different fallback UI based on the type of error.
componentDidCatch
method, you would send the error information to the error reporting service.