What Is ErrorBoundary in React and When To Use It

Making good use of this feature can make your code more robust

Stephanie Zhan
Level Up Coding

--

Photo by Voice + Video on Unsplash

It’s easy for us to write JSX in React, but when building large applications, you might forget about error handling. In JS we can simply use try...catch to catch errors, but in React we can use ErrorBoundaries to gracefully handle runtime errors. This article will introduce how it works and when to use it.

What is ErrorBoundary?

ErrorBoundary is a higher-order component (HOC) in React that catches runtime errors that occur during the rendering phase of a component tree. When an error is caught by the ErrorBoundary, it renders a fallback UI instead of crashing the whole application. This allows the application to recover from the error and continue rendering other components.

How does ErrorBoundary work?

ErrorBoundary works by wrapping a component that may throw an error in a try...catch block. If an error is thrown during the rendering of the component, the catch block is executed, and the ErrorBoundary component can then handle the error and display a fallback UI.

Here’s an example of how to create an ErrorBoundary component:

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
console.log(error, errorInfo);
}

render() {
if (this.state.hasError) {
// Fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}

In the above code, we create an ErrorBoundary component that has a constructor that initializes the state with a boolean value hasError set to false. When an error occurs, getDerivedStateFromError is called and updates the state, which triggers a re-rendering of the ErrorBoundary component.

The componentDidCatch method is also called when an error occurs, and it logs the error to the console. You can also use this method to log the error to an error reporting service.

The render method of the ErrorBoundary component checks the hasError state. If hasError is true, it renders a fallback UI. If not, it renders its children.

By default, React will remove its UI from the screen if your application throws an error during rendering. Through the above processing, we can display the backup UI to the user.

When should I use ErrorBoundary?

ErrorBoundary should be used to handle errors that occur during the rendering phase of a component tree. In other words, when an error occurs in a component’s render method or in any of its child components render methods.

It’s important to note that ErrorBoundary should not be used to handle errors that occur during the lifecycle methods of a component, such as componentDidMount or componentDidUpdate. Instead, you should use try-catch blocks or other error-handling mechanisms within these methods.

Here are some scenarios where you might want to use ErrorBoundary:

Third-party libraries or APIs that may throw errors

When you’re using third-party libraries or APIs, there’s always a chance that they might throw errors. By wrapping the component that uses these libraries or APIs in an ErrorBoundary, you can ensure that your application doesn’t crash if an error occurs.

class MyComponent extends React.Component {
render() {
return (
<ErrorBoundary>
<ThirdPartyComponent />
</ErrorBoundary>
);
}
}

In the above code, we wrap the Third PartyComponent in an ErrorBoundary to ensure that any errors thrown by the third-party library are caught and handled gracefully.

Unpredictable user input

If your application allows users to input data, there’s always a chance that they might enter invalid or unexpected data. By wrapping the component that displays user input in an ErrorBoundary, you can ensure that your application doesn’t crash if an error occurs due to invalid or unexpected user input.

class UserInputComponent extends React.Component {
render() {
const userInput = this.props.userInput;
return (
<ErrorBoundary>
<div>{userInput}</div>
</ErrorBoundary>
);
}
}

In the above code, we wrap the div that displays user input in an ErrorBoundary to ensure that any errors thrown due to invalid or unexpected user input are caught and handled gracefully.

Legacy code or code with unknown error sources

If you’re working with legacy code or code with unknown error sources, it can be difficult to predict where errors might occur. By wrapping the component tree in an ErrorBoundary, you can ensure that any errors that occur during rendering are caught and handled gracefully.

class MyApp extends React.Component {
render() {
return (
<ErrorBoundary>
<LegacyComponent />
</ErrorBoundary>
);
}
}

In the above code, we wrap the LegacyComponent in an ErrorBoundary to ensure that any errors that occur in the legacy code are caught and handled gracefully.

Conclusion

React ErrorBoundary is a powerful feature that helps developers handle runtime errors gracefully. By wrapping components that may throw errors in an ErrorBoundary, developers can ensure that their applications don’t crash if an error occurs during rendering.

Also, you don’t need to wrap every component into a separate error boundary. When you think about the granularity of error boundaries, consider where it makes sense to display an error message. It’s also worth mentioning that there is currently no way in React to wrap ErrorBoundary which is written as a function component, sometimes you don’t have to write it yourself, the community provides react-error-boundary similar libraries to help you.

Thanks for reading, catch you in the next one, cheers 🍻

Not a Medium member? Support me here by becoming one.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--