Error Boundaries in React

Tich
2 min readNov 4, 2023
Photo by Lautaro Andreani on Unsplash

A JavaScript error can occur within a component of your UI during the rendering process, potentially causing your entire application to crash. This happens because, by default, React will remove its UI from the screen, leading to a situation where your application’s interface becomes blank.

This is where Error boundaries come to the rescue.

Error Boundaries

An Error Boundary is a special type of component that is used to capture errors that occur during the rendering of its child components, log the errors, and display a fallback UI. They provide a way to gracefully handle errors without compromising the overall user experience.

Implementing Error Boundaries

To create an error boundary component, you should include a static method called getDerivedStateFromError. This method allows you to update the component’s state in reaction to an error and present an error message to the user. Additionally, you have the option to implement componentDidCatch to incorporate extra functionality, such as logging the error to an analytics service or error tracking service like Sentry.

The following is an example I got from the React docs:

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, info) {
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
logErrorToMyService(error, info.componentStack);
}

render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return this.props.fallback;
}

return this.props.children;
}
}

To use this error boundary, wrap it around the component or components that you want to protect:

<ErrorBoundary fallback={<p>An application error has occurred</p>}>
<YourComponent />
</ErrorBoundary>

Best Practices:

Use Error Boundaries sparingly:

They are best suited for unexpected errors, not for handling everyday logic or validation errors.

Log Errors:

Log errors to a service like Sentry, for debugging and monitoring purposes.

--

--

Tich

JavaScript || Reactjs || Typescript || SQL || .Net