Global error handling in React Js

Last updated : July 23, 2022

An uncaught Javascript error can crash the entire app. The Error Boundary is a concept introduced to prevent app crashes by catching Javascript errors at the higher application level. Error Boundaries are React class components that wrap up all child components and catch their errors. The componentDidCatch callback detects the errors. Therefore, the Error Boundary component must be a class component. There is no equivalent in functional React components.

Here is an example of an Error Boundary class component.

import React, { ErrorInfo, ReactElement } from "react";
interface ErrorBoundaryState {
    hasError: boolean
    errorMessage: string
interface ErrorboundaryProps {
    children: ReactElement
export class ErrorBoundaries extends React.Component<ErrorboundaryProps, ErrorBoundaryState>{
    constructor(props: ErrorboundaryProps){
        this.state = {
                        hasError : false,
                        errorMessage: ""
    componentDidCatch(error: Error, errorInfo: ErrorInfo){
        this.setState({hasError: true})
        this.setState({errorMessage: error.message})
        //Do something with err and errorInfo
    render(): React.ReactNode {
                <div className="divClass">

Next, we must wrap all the components we want to protect against errors.

import { ErrorBoundaries } from "./components/ErrorBoundaries"
import SuccessMessage from "./components/SuccessMessage"
export const App = () => {
export default App

That prevents app crashes due to any errors in the SuccessMessage component. For demo purposes, I throw an error in the useEffect hook. Since this error is not caught within the SuccessMessage component, it will bubble up until it finds the ErrorBoundary component capable of handling the error.

import { useEffect } from "react"
const SuccessMessage = () =>{
  useEffect(() => {
    throw new Error("Api did not respond!")// throwing an error
            <span>Your Account has been created successfully</span>
            <button>Go to account</button>
export default SuccessMessage
React js global error handling with error boundaries
Figure 1: React js global error handling with error boundaries
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments