Error Boundaries 👾🤖

Shubham Khandal
3 min readSep 10, 2022

--

In the past, if we encountered any JavaScript errors inside components, they would corrupt React’s internal state and render React inoperable. React components don’t offer any solutions for dealing with these errors, nor does it offer any ways to recover from them.☠️😵😮👇

But, React 16 introduces a new concept to handle the errors by using the error boundaries. Now, if any JavaScript error is found in a part of the UI, it does not break the whole app.👨‍💻👀👍

Introduction

  1. Error boundaries are React components that catch JavaScript errors anywhere in our app, log those errors, and display a fallback UI.
  2. It does not break the whole app component tree and only renders the fallback UI whenever an error occurred in a component.

3. Error boundaries catch errors during rendering in component lifecycle methods, and constructors of the whole tree below them.

The Problem —

React v16 introduced the concept of “error boundaries”.

This solution —

Error boundary in class ☠️

If a class component implements either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch, then the class becomes an error boundary. After an error has been thrown, use static getDerivedStateFromError() to render a fallback UI. To record error information, use componentDidCatch().

How to implement error boundaries ☠️

  1. Create a class that extends React component and passes the props inside it.
  2. Now, add the componentDidCatch() method which allows you to catch errors in the components below them in the tree.
  3. Next, add the render() method, which is responsible for how the component should be rendered.

For example, it will display the error message like
“Something is wrong.👻

Error Boundary in Event Handler ☠️

Error boundaries do not allow catching errors inside event handlers. React does not need any error boundary to recover from errors in the event handler.

In the below example, you can see how an event handler will handle the errors. 👾

If there is a need to catch errors in the event handler, you can use JavaScript try-catch statement.

So,

🙂I hope you are understood all approaches to Error Boundaries. I have one more way to handle Error Boundaries and we will discuss 🤔 in the next article about this. 🧐🤓

🙏Thanks, Guys for your valuable time 👋

👉 For more information pls click on 👾👻 💀 ☠️

--

--

Shubham Khandal
Shubham Khandal

Written by Shubham Khandal

👋 Hi, I’m shubham khandal 👀 I’m interested in React & JavaScript. 🌱 I’m always in learning mode. 💞️ I collaborate on React & JavaScript Projects..

No responses yet