Using react-error-boundary, handle errors in React

Using react-error-boundary, handle errors in React

Using react-error-boundary, handle errors in React

Whether they are edge cases, server-related problems, or other types of faults, mistakes will inevitably occur in our apps. As a result, numerous techniques have been created to stop these problems from affecting the user and developer experience. One such approach in React is the use of error boundaries.

Boundaries for errors in React:

In order to detect and handle JavaScript problems that happen in the UI components of our component, error boundaries were added to React 16 in version 1. Therefore, error boundaries only detect problems that happen inside Hooks like useEffect, lifecycle methods, and render methods. The React documentation states that error borders do not address mistakes in:

·        handlers of events

·        Asynchronous code (e.g., setTimeout or requestAnimationFrame callbacks)

·        rendering on the server

·        In the error boundary itself thrown errors (rather than its children)

Therefore, error boundaries essentially only deal with mistakes in the portions of our code that use React.

Simply define a state variable to track if the error boundary has detected an error and a class component to create an error boundary. Additionally, our class component must to have three at least:

1.     The error boundary's state is updated using the static function getStateFromError.

2.     When our error boundaries detect an error, there is a componentDidCatch lifecycle method for carrying out actions, including logging to an error logging service.

3.     A render function for rendering the fallback UI in the event of an error or the child of our error boundary.

Here is an illustration of what our basic error border should seem, derived from the React documentation:

class ErrorBoundary extends React.Component {

 constructor(props) {

   super(props);

   this.state = { hasError: false };

 }

 

 static getStateFromError(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

   logErrorMyService(error, errorInfo);

 }

 

 render() {

   if (this.state.hasError) {

     // You can render any custom fallback UI

     return <h1>Something went wrong.</h1>;

   }

 

   return this.props.children;

 }

}

 

No alt text provided for this image

 

react-error-boundary:

Developers can use react-error-boundary, a wrapper over React's error boundary, to implement error boundaries in code without having to create them from scratch. With react-error-boundary, we can easily surround components where we anticipate issues with the ErrorBoundary component that is already given and pass in additional props to modify the behaviour of our error boundary.

In this article, I'll go over how to handle failures in a React application using react-error-boundary. Let's examine the services the library provides.

component for error boundaries:

The primary component offered by react-error-boundary is the ErrorBoundary component. With less code, it enables us to implement the normal React error border.

Here's an example of how ErrorBoundary can be used:

function App(){

 ...

 return (

   <ErrorBoundary

     fallbackRender = {({error, resetErrorBoundary, componentStack}) => (

         <div>

         <h1>An error occurred: {error.message}</h1>

         <button onClick={resetErrorBoundary}>Try again</button>

       </div>

     )}

   >

     <ComponentThrowAnError/>

   </ErrorBoundary>

 );

}

To render our fallback component if there is an error (that can be detected and handled by react-error-boundary), we simply wrap our component in the ErrorBoundary component in the component shown above and send our fallback component to the FallbackComponent parameter.

Additionally, we have the fallbackRender prop, a render prop-based API that allows us to declare our fallback component inline. This code block uses the fallbackRender prop and is displayed above:

function App(){

 ...

 return (

   <ErrorBoundary

     fallbackRender = {({error, resetErrorBoundary, componentStack}) => (

         <div>

         <h1>An error occurred: {error.message}</h1>

         <button onClick={resetErrorBoundary}>Try again</button>

       </div>

     )}

   >

     <ComponentThrowAnError/>

   </ErrorBoundary>

 );

}

Additionally, the ErrorBoundary contains a onError property that serves as a listener and is activated whenever our error boundary detects and responds to an error in one of its child components. We can opt to report these failures from here to whichever error logging service we may be utilising.

function App(){

 ...

 

 return (

   <ErrorBoundary

     onError = {(error, componentStack) => {

       logToLoggingService(error, componentStack);

     }}

     ...

   >

     <ComponentThrowAnError/>

   </ErrorBoundary>

 );

}

To view or add a comment, sign in

More articles by Skill Gain

  • Do you know how to use Scroll View?

    UIScrollView is a widget or component in UIKit that allows users to scroll through content that is larger than the…

  • Machine Learning

    MACHINE LEARNING Machine learning is a field of study that has gained a lot of attention in recent years due to its…

  • JWT Authentication

    Why JWT? When we are working on PHP we can use SESSION for authentication, but when we will use API in a third-party…

  • CSRF Protection in Flask

    Let's carry out a quick Flask project to demonstrate how you can manually safeguard your data with CSRF protection. In…

  • Dynamic URLs Variable Rule in Flask

    Dynamic URLs Variable Rule in Flask This article will go through Python's Flask-Variable Rule. With no database…

  • Query Parameters with Multi-Value in Flask A

    Python-based Flask is a micro-framework. It is well-known for creating RESTful APIs since it is lightweight and simple…

  • Introducing the React Hook for Sound Effects "use-sound"

    Introducing the React Hook for Sound Effects "use-sound" Use the React hook use-sound to play sound effects. This is a…

  • How to Create Spinners In Android?

    Android Spinner is a view that resembles a drop-down menu and is used to select a single option from a list of options.…

  • Useful Custom Hooks That You Need To Add Into Your React Project (Part II)

    Useful Custom hooks that You need to add into your React Project : Hooks are great for extracting logic into reusable…

  • A Brief on React Helmet (Part 1)

    React Helmet Every website developer hopes that his or her website will show up first in the browser's search results…

Others also viewed

Explore content categories