Return to site

REACT: Handling errors with ErrorBoundary

· react

In React, an error boundary is a component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed.

Here's an example of how to use error boundaries in React:

import React, { Component } from 'react'
class ErrorBoundary extends 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) {
    // Log the error to an error reporting service
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}


// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>;

 

In this example, ErrorBoundary is a component that catches errors and displays a fallback UI.

The getDerivedStateFromError method updates the state so that the fallback UI is displayed, and the componentDidCatch method logs the error to the console.

The children prop is used to render the child components of the ErrorBoundary component.

By using error boundaries in your React application, you can provide a better user experience by displaying a useful error message when something goes wrong.

Check the code👇👇👇

 

 

Section image