ReactJS (V 16.*) Error handling with new lifecycle method.
In the past, if you get a runtime error inside the components it used to break Component's state. Sometimes your entire application will break. But react didn't give any option for handling this kind of runtime errors, and could not recover from them as well.
But from version 16.0.* React introduced a new concept called Error Boundaries.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
The new component lifecycle of React may look like below.
It introduced a new lifecycle method called componentDidCatch(err, info). This function works very similar to javascript catch function in try-catch blocks but in a little different way.
Example of Error boundary:
import Raven from "raven";
Raven.config("SENTRY_DSN").insall();
// Sentry.io configuration
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log your error to error sevices like Sentry.io
// You can use other error services also.
Raven.captureException(error, { extra: info });
});
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UIreturn <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
The above component ErrorBounday now acts as an error boundary. This can be used a normal react component. as shown below.
// Your compoent should be wrapped inside the ErrorBoundaryComponent
<ErrorBoundary>
<YourComponent />
</ErrorBoundary>
Now, whenever there is an error in the YourComponent (which is uncaught). That error will be passed to the lifecycle method componentDidCatch of the ErrorBoundary component.
Note:
- The componentDidCatch of ErrorBoundary will not catch errors of its own.
- If an error message was caught by a one error boundary it'll not get propagated to the next error boundary.
- As React 16 if your application is having an errors that were not caught by any error boundaries, then your whole application will get unmounted.
Using these error boundaries is up to you. You can place error boundaries wherever you want. But I recommend to use it on the top of your application like Router.