React: Error handling (Avoid blank screens using error boundaries)(HOC)

Image for post
Image for post
Photo by Markus Spiske on Unsplash

What are error boundaries?

They are the simple fallback options provided by React(¹⁶) itself, that allows you to show a proper fallback UI or an error message.

No blank screen will be shown on production or any environment except local, where you’ll see the line number of error causing code.

Prerequisite knowledge

Lifecycle methods used:

static getDerivedStateFromError(error) { /* LOGIC GOES HERE */}

This method is static and basically identifies any error thrown and catches the error, hence we write state-change logic here.

componentDidCatch(error, errorInfo) { /* LOGGING ERROR */ }

This is the lifecycle method provided by React that takes two arguments error and the info of the error, this method runs after the error is caught.

Files are available on my Github repo.

Getting Started

Step 1: Make the component that catches the error:

import React from “react”;class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: { message: “”, stack: “” },
errorInfo: { componentStack: “” },
};
}
// Catches the error and changes the state
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
/* This lifecycle method is optional if you do not want to log error information */
// Logs the error into the state
componentDidCatch = (error, errorInfo) => {
// Sets the error and info in state
this.setState({ error, errorInfo });
};
render() {
if (this.state.hasError && !this.props.showErrorComponent) {
// You can render any custom fallback UI
return <div className=”error”>ANY MODAL OR POP_UP COMPONENT HERE</div>;
}
/* Condition if we do not want to show modal or any component that you chose everytime, instead we have some text or other component. */
else if (this.state.hasError && this.props.showErrorComponent){
return <h1>Some error!</h1>;
}

// Else return the children as is
return this.props.children;
}
}
export default ErrorBoundary;

Step 2: Making an HOC (Higher-order Component):

This component could be kept in the molecules folder of your project.

Since we have to re-use it and it is an HOC we can keep it in a separate folder of HOCs as well, whatever suits you the best.

/* 2nd param is if we want to show the 1st fallback component, else just the text <h1>Some error!</h1> */export function withErrorBoundary(WrappedComponent, showErrorComponent = false) {
return props => (
<ErrorBoundary showErrorComponent={showErrorComponent}>
{/* This👇🏼 is the component wrapped in boundary */}
<WrappedComponent {...props} />
</ErrorBoundary>
);
}

Step 3: Using the Boundary component:

This would be the normal component either functional or class-based, and we just have to wrap the component up within the HOC we made.

For example- How to export the component when:

Image for post
Image for post
Case: When we are showing 1st fallback UI

Case 1: When we want to show fallback component.

(Here Just a text in red color shows when count gets = 5)

import { withErrorBoundary } from “<PATH>/ErrorBoundary”;class Child1 extends Component {
/* Component code */
}
export default withErrorBoundary(Child1);
Image for post
Image for post
Case: When we are showing 2nd fallback UI

Case 2: : When we want to show just error message OR

1st type of error: here(plain text)


import import { withErrorBoundary } from “<PATH>/ErrorBoundary”;
class Child2 extends Component {
/* Component code */
}
export default withErrorBoundary(Child2, true);

Case 3: When component is connected to redux/store:

import { connect } from "react-redux";
import import { withErrorBoundary } from “<PATH>/ErrorBoundary”;
class IAmInsideBoundary extends Component {
/* Component code */
}
export default connect(mapStateToProps, mapDispatchToProps)withErrorBoundary(MeInsideBoundary, true));

Wondering, why is still this error page coming?

Image for post
Image for post

Don’t worry, it is just because we are working in the localhost environment, and for the sake of development/debugging and ease of developers, this page still pops up in the development environment. This won’t be there in higher environments.

You can use the HOC component in many other creative ways depending upon your requirements. :)

FullStack Js Developer, Specialization in ReactJs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store