
Error Boundaries in React
19 January, 2023
2
2
0
Contributors
Error boundaries in class components
In React, error boundaries are a feature that allows you to catch and handle JavaScript errors that occur within a specific part of your application. An error boundary is a component that implements a lifecycle method called componentDidCatch
, which is invoked whenever an error occurs within the component or its children. This lifecycle method allows you to handle the error, display an error message, or fallback UI, or log the error message for debugging purposes.
In functional components
Error boundaries in functional components work similarly to how they work in class-based components. Error boundaries for functional components are typically implemented as Higher-Order Components (HOC) that wraps a functional component, and handle errors that occur within the wrapped component.
Example of error boundary
Here's an example of an error boundary implemented as an HOC:
import React, { useState } from 'react';
function withErrorBoundary(WrappedComponent) {
return function ErrorBoundary(props) {
const [error, setError] = useState(null);
if (error) {
return <div>An error occurred: {error.toString()}</div>;
}
try {
return <WrappedComponent {...props} />;
} catch (err) {
setError(err);
}
}
}
export default withErrorBoundary;
In this example, the withErrorBoundary
HOC takes a functional component as an argument, and returns a new functional component that wraps the original component. The new component uses the useState
hook to keep track of any errors that occur, and if an error occurs, it will render a fallback UI. The wrapped component is then rendered inside a try-catch
block, so that any errors that occur in it will be caught and handled by the HOC.
To use this HOC, you would import it and wrap the component that you want to handle errors for:
import withErrorBoundary from './withErrorBoundary';
function MyComponent() {
// ...
}
export default withErrorBoundary(MyComponent);
It's worth noting that the functional error boundary components only catch errors in the wrapped component and its children. If there are other components higher in the component tree, you need to wrap those components as well, and make sure that the HOC is the outermost component, in order to catch all errors throughout the component tree.
Summary
As with class-based components error boundaries, functional error boundaries are a powerful feature that allows you to handle errors gracefully and maintain the stability of your application, by providing a fallback UI when errors occur, and prevent the application from crashing.