Categories
React Answers

How to Use React Error Boundaries to Handle Errors Gracefully?

Spread the love

We can use React error boundaries to handle errors gracefully in a React app.

In this article, we’ll look at how to use React error boundaries to handle errors gracefully in a React app.

Use React Error Boundaries to Handle Errors Gracefully

Error boundaries are components that are displayed when there’re errors. They have special hooks like componentDidCatch to let us retrieve error details and does actions on error accordingly.

We wrap error boundary components around components that may throw errors for them to work.

Error boundary components are always class-based components. There’s no function component equivalent for this.

For instance, we can define an error boundary component and use it as follows:

import React from "react";
`
function Foo() {
  throw new Error("error");
  return <div>foo</div>;
}
`
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {
      return <h1>Error occurred.</h1>;
    }
    return this.props.children;
  }
}
`
export default function App() {
  return (
    <ErrorBoundary>
      <Foo />
    </ErrorBoundary>
  );
}

In the code above, we defined the ErrorBoundary component, which has the componentDidCatch hook, which takes the error parameter with the error that’s raised, and info object with the error information.

Then we call setState to hasError to true so that we render an error message. We return this.props.children when there’re no errors so that we display the components that we put inside the ErrorBoundary component.

Therefore, when we have Foo , where we threw an error, then we display the ‘Error occurred’ message since Foo throws an error before rendering anything.

Conclusion

Error boundaries are components that are displayed when there’re errors. They have special hooks like componentDidCatch to let us retrieve error details and does actions on error accordingly.

We wrap error boundary components around components that may throw errors for them to work.

Error boundary components are always class-based components. There’s no function component equivalent for this.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *