avatarkirti kaushal

Summary

The provided content is a comprehensive guide on implementing Error Boundaries in React applications to handle errors gracefully and display a fallback UI.

Abstract

The article "How to use Error Boundaries with Fallback UI in React?" is a detailed tutorial aimed at React developers, particularly those new to the framework. It explains the concept of error boundaries introduced in React 16, which are components that catch and handle JavaScript errors in their child component tree. The article covers the importance of error boundaries in logging errors and displaying a user-friendly UI when part of the application crashes. It also discusses the limitations of error boundaries, such as not catching errors in event handlers or asynchronous code. The tutorial guides readers through setting up a React app, creating an error boundary component using getDerivedStateFromError and componentDidCatch lifecycle methods, and demonstrating how to test the error boundary functionality with a sample application. Additionally, it provides insights into interpreting component stack traces and emphasizes the necessity of error boundaries for a robust error handling strategy in React applications.

Opinions

  • The author, Kirti Kau, advocates for the use of error boundaries as an essential tool for React developers to ensure a resilient user experience.
  • The article suggests that error boundaries are a significant improvement over the limited error handling capabilities of React versions prior to 16.
  • It is implied that while try/catch is useful for imperative code, error boundaries are necessary for declarative components in React.
  • The author emphasizes the importance of logging errors and providing a fallback UI to maintain user trust, especially in production environments.
  • There is an opinion that using a class component is currently the only way to create an error boundary in React, despite the trend towards functional components.
  • The author provides a subjective recommendation to use Create React App for easy setup of source maps, which aids in debugging with better stack traces.
  • The article conveys that error boundaries should be disabled in production mode to avoid performance penalties, indicating a best practice for React application deployment.
  • It is mentioned that error boundaries are not a catch-all solution, and developers should still use traditional try/catch for certain scenarios, such as within event handlers and asynchronous code.

How to use Error Boundaries with Fallback UI in React ?

How to use Error Boundaries with Fallback UI in React

The following article will help you to understand how to use Error boundaries in React Beginner Guide

React users, React 16 introduces a new concept of an “error boundary”. React 15 included a very limited support for error boundaries under a different method name: unstable_handleError.

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

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

Before we start in detail regarding the error boundaries please find below important .

Uncaught Errors

Uncaught means the error was not caught in a catch statement, and TypeError is the error’s name. undefined is not a function.

JavaScript TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function. This error occurs in Chrome Browser when you read a property or call a method on an undefined object .

Component Stack Traces

React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces.

In computing, a stack trace (also called stack backtrace or stack traceback) is a report of the active stack frames at a certain point in time during the execution of a program. … Each time a function is called in a program, a block of memory called an activation record is allocated on top of the call stack.

A stack trace is a list of the functions, in order, that lead to a given point in a software program. A stack trace is essentially a breadcrumb trail for your software. You can easily see the stack trace in JavaScript by adding the following into your code: console. trace();

You can also see the filenames and line numbers in the component stack trace. This works by default in Create React App projects:

If you don’t use Create React App, you can add this plugin manually to your Babel configuration.

Note that it’s intended only for development and must be disabled in production.

Fallback UI

A display of a beautiful UI (HTML and CSS) instead if error when something broke in the code.

Example as below

FALLBACK UI SCREEN

How to avoid errors in Javascript

Exceptions, whether sync or async, go up the stack until there is a try..catch to handle them.

try / catch is great but it only works for imperative code:

try {
  showUser();
} catch (error) {
  // ...
}

Download tools :

  1. Nodehttps://nodejs.org/en/download/
  2. Visual Studio or any editor for coding —
  3. Chrome browser
  4. React version → > 16.8

HOW TO START —

Error Boundary

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch().

Two Important points before creating the error boundaries

  1. Only a class component can be used as an error boundary.

Even if you’re writing all your components as function, you still have to make use of a class component if you want to have an error boundary.

2. It must define either (or both) of static getDerivedStateFromError() or componentDidCatch().

ADVANTAGES

1. Catch JavaScript Errors

2. Logs errors

Use static getDerivedStateFromError() to render a fallback UI after an error has been thrown.

3. Fallback Fancy UI (Can generate the Fancy or User friendly UI)

Use componentDidCatch() to log error information.

DISADVANTAGES

  1. Error boundaries do not catch errors inside event handlers.
  2. React doesn’t need error boundaries to recover from errors in event handlers.
  3. If you need to catch an error inside an event handler, use the regular JavaScript try / catch statement.

Error boundaries do not catch errors for:

  • Event handlers
  • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
  • Server side rendering
  • Errors thrown in the error boundary itself (rather than its children)

Step 1.

First, we need the react app with some basic routing — so if you are new to react please follow the below article on how to start with React CRA :)

Step 2.

Clone any react app — to create the error boundaries example , i am using below repo for clone and create new branch for ErrorBoundaries

git clone https://github.com/kirti/react-data-fetching-axios-fetchapi.git

Step 3.

yarn install
yarn start 

Step 4.

open the browser https://localhost:3000 — working project

LocalHost Project

Step 5.

Now we will add error boundaries in the working code and will also add some error to reproduce the FallBack Error UI

Let’s start

a) Create the ErrorBoundary.js and add the below code — Noted down it should be class component

Only a class component can be used as an error boundary

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch().

ErrorBoundary.js

import React from 'react'
import ErrorFallback from './ErrorFallback'
export 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
//logErrorToMyService(error, errorInfo);
console.log(error, errorInfo)
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <ErrorFallback></ErrorFallback>;
}
return this.props.children;
}
}

b) ErrorFallback UI for fallback fancy UI instead of just error.

Create the ErrorFallback.js 
Sample HTML (free downloaded from https://freefrontend.com/500-error-page-html-templates/) — 
You can also use any html as per your design or requirement.

Code reference

STEP 6.

Example: Open the App.js file. Here, App is our default component where we have written our code for Errorboundary wrapper.

Github Code

Open the App.js

STEP 7.

How to test Error Boundaries is working ?

a) Open the PostsWithAxios.js

and add some code which can reproduce some error in javascript

For example —

check line 19 of below file (Github code) post.name.toUppercase —

this is error because name is not in response api and if we convert to toUpperCase for undefined it will give error and break the UI

Step 8.

yarn start

Step 9.

Open the browser with http://localhost:3000

Click Here — Posts With Axios Example

or

Open direct axios url http://localhost:3000/axios

Development Environment —

You will first see below screen with complete component trace

Production Behaviour

Github Code —

Conclusion:

This is the explanatory medium story of How to use Error Boundaries with Fallback UI in React If you have any doubts, please mail me at [email protected]

Happy Learning and Stay Safe.

Take care All

Please find my few more articles for beginners :)

Share knowledge and kind is cool :)

React Js Tutorials
Error Handling
Error Boundaries
JavaScript
Try And Error
Recommended from ReadMedium