Error Boundaries in React

Error Boundaries in React

By - Sarika kore10/13/2025

Building reliable and user-friendly applications is one of the main goals of every React developer. While React provides an efficient and flexible way to create user interfaces, even the best applications can encounter unexpected errors — whether due to a bug in a component, incorrect API response, or a third-party integration issue. Learn Error Boundaries in React to handle runtime errors gracefully, improve app stability, and provide a better user experience in React applications.

 

Without proper error handling, these issues can crash entire sections of your app, creating a frustrating user experience. To address this, React introduced Error Boundaries — a powerful feature that allows developers to handle runtime errors gracefully in React components.

 

What Are Error Boundaries?

Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of crashing the entire app.

In simple terms, think of them as try-catch blocks for React components. While JavaScript’s try-catch works for imperative code, Error Boundaries are the declarative way to handle errors in React’s component tree.

When an error occurs during rendering, in lifecycle methods, or in constructors of child components, an Error Boundary can catch that error and display an alternative UI — often a simple “Something went wrong” message — while keeping the rest of the application running smoothly.

 

When and Where Error Boundaries Work

Error Boundaries can catch errors in the following cases:

  • • During the rendering of components.
  • • Inside lifecycle methods (like componentDidMount, componentDidUpdate).
  • • Within the constructors of class components.


However, they do not catch errors in the following cases:

  • • Inside event handlers (you must use try-catch manually here).
  • • Asynchronous code, such as callbacks, setTimeout, or Promises.
  • • Server-side rendering (SSR).
  • • Errors thrown inside the error boundary itself.

 

 

Why Do We Need Error Boundaries?

React applications can become complex very quickly. A small bug in one component can potentially crash the entire app if not handled correctly.

Let’s consider a scenario — you have a dashboard where multiple widgets render data from different APIs. If one widget crashes due to a bad API response, it should not break the entire dashboard. Instead, you can wrap each widget with an Error Boundary so that only the faulty one shows an error message while others continue working.

This leads to:

  • • Improved user experience – the app doesn’t crash entirely.
  • • Better debugging – developers get clear insights into which part failed.
  • • Graceful recovery – users can retry, reload, or continue using other sections.

 

Creating an Error Boundary

Error Boundaries can only be created using class components

Example: Basic Error Boundary

import React from "react";

 

class ErrorBoundary extends React.Component {

  constructor(props) {

    super(props);

    this.state = { hasError: false };

  }

 

  static getDerivedStateFromError(error) {

    // Update state to display fallback UI

    return { hasError: true };

  }

 

  componentDidCatch(error, info) {

    // Log error details for debugging

    console.error("Error caught by Error Boundary:", error, info);

  }

 

  render() {

    if (this.state.hasError) {

      // You can render any custom fallback UI

      return <h2>Something went wrong. Please try again later.</h2>;

    }

    return this.props.children;

  }

}

 

export default ErrorBoundary;

Using the Error Boundary

import ErrorBoundary from "./ErrorBoundary";

import MyWidget from "./MyWidget";

 

function Dashboard() {

  return (

    <div>

      <ErrorBoundary>

        <MyWidget />

      </ErrorBoundary>

    </div>

  );

}

Now, if MyWidget throws an error while rendering, React will catch it and display the fallback message instead of crashing the entire dashboard.

Explore Other Demanding Courses

No courses available for the selected domain.

Example: Error Boundary in Action

import React from "react";

 

class BuggyCounter extends React.Component {

  constructor(props) {

    super(props);

    this.state = { count: 0 };

  }

 

  handleClick = () => {

    this.setState(({ count }) => ({ count: count + 1 }));

  };

 

  render() {

    if (this.state.count === 5) {

      throw new Error("Counter crashed!");

    }

    return <h3 onClick={this.handleClick}>{this.state.count}</h3>;

  }

}

 

class ErrorBoundary extends React.Component {

  constructor(props) {

    super(props);

    this.state = { hasError: false };

  }

 

  static getDerivedStateFromError() {

    return { hasError: true };

  }

 

  componentDidCatch(error, info) {

    console.log("Error:", error, info);

  }

 

  render() {

    if (this.state.hasError) {

      return <h2>Something went wrong with the counter.</h2>;

    }

    return this.props.children;

  }

}

 

export default function App() {

  return (

    <div>

      <ErrorBoundary>

        <BuggyCounter />

      </ErrorBoundary>

      <ErrorBoundary>

        <BuggyCounter />

      </ErrorBoundary>

    </div>

  );

}

In this example, clicking on a counter increases its value. When the count reaches 5, it deliberately throws an error. Because each counter is wrapped in its own Error Boundary, only the faulty counter displays the fallback message, while the other continues working normally.

 

Handling Errors in Functional Components

React doesn’t yet provide hooks-based APIs for creating error boundaries directly in functional components. However, you can still use Error Boundary components to wrap functional components.

Alternatively, libraries like react-error-boundary by Kent C. Dodds offer a simpler way to implement this in functional components using hooks and render props.

Example using react-error-boundary:

import { ErrorBoundary } from "react-error-boundary";

 

function FallbackComponent({ error, resetErrorBoundary }) {

  return (

    <div>

      <p>Something went wrong: {error.message}</p>

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

    </div>

  );

}

 

function BuggyComponent() {

  throw new Error("Oops!");

}

 

export default function App() {

  return (

    <ErrorBoundary

      FallbackComponent={FallbackComponent}

      onReset={() => console.log("Reset!")}

    >

      <BuggyComponent />

    </ErrorBoundary>

  );

}

This modern approach provides a clean way to manage errors while keeping components functional.

 

Best Practices for Using Error Boundaries

Here are some practical tips to get the most out of Error Boundaries:

  1. 1. Wrap critical UI sections – Use Error Boundaries around key components like dashboards, widgets, or routes.
  2. 2. Provide user-friendly fallback UI – Instead of generic text, show meaningful recovery options (e.g., “Reload page” or “Go back”).
  3. 3. Log errors – Use services like Sentry or LogRocket to record caught errors for debugging.
  4. 4. Keep boundaries small and focused – Avoid wrapping the entire app with a single boundary; use multiple small ones for modular handling.
  5. 5. Use for production safety – Don’t rely on them for debugging; use them to prevent app crashes in production environments.

Error Boundaries are a crucial part of building resilient React applications. They ensure that a single broken component doesn’t compromise the entire user interface.

By catching rendering errors and displaying fallback UIs, Error Boundaries help maintain a seamless experience, allowing users to continue interacting with unaffected parts of your app.

 

In short:

Error Boundaries don’t prevent bugs, but they make your app more resilient when bugs appear.

Do visit our channel to explore more: SevenMentor

Author :- Sarika kore

Get Free Consultation

Loading...

Call the Trainer and Book your free demo Class..... Call now!!!

| SevenMentor Pvt Ltd.

© Copyright 2025 | SevenMentor Pvt Ltd.

Share on FacebookShare on TwitterVisit InstagramShare on LinkedIn