codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚛️

React.js

40 / 61 topics
40Error Boundaries in React41Handling Errors in Class Components42Using the Error Boundary API
Tutorials/React.js/Error Boundaries in React
⚛️React.js

Error Boundaries in React

Updated 2026-04-20
3 min read

Introduction

In this tutorial, we will explore Error Boundaries in React, a powerful feature designed to handle JavaScript errors that occur during rendering, lifecycle methods, and constructors of the entire component tree below them. By using error boundaries, you can prevent your application from crashing and provide users with a better experience by displaying a fallback UI.

What are Error Boundaries?

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. They work like a try-catch block but for React components.

Key Characteristics

  • Catch Errors: Capture JavaScript errors in their child component tree.
  • Fallback UI: Render a fallback UI when an error occurs.
  • Contain Errors: Prevent errors from propagating to the rest of the application.
  • Class Components Only: Error Boundaries are implemented as class components.

Implementing Error Boundaries

To create an Error Boundary, you need to define a class component that implements either or both of the lifecycle methods static getDerivedStateFromError() and componentDidCatch(). These methods allow you to update the state and log errors respectively.

Step 1: Define the Error Boundary Component

import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    // Initialize state to manage error status
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    console.error("An error occurred:", error);
    console.error("Component stack:", info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    // Normally, just render children
    return this.props.children;
  }
}

export default ErrorBoundary;

Explanation

  • constructor(props): Initializes the component's state with hasError: false.
  • static getDerivedStateFromError(error): This lifecycle method is called when an error occurs in a child component. It receives the error as an argument and returns an object to update the state.
  • componentDidCatch(error, info): This lifecycle method is also called when an error occurs. It receives both the error and additional information about the error (like the component stack). Here, you can log errors or perform other side effects like sending error reports.
  • render(): If hasError is true, it renders a fallback UI; otherwise, it renders its children.

Step 2: Using the Error Boundary

You can wrap any part of your component tree with an Error Boundary to protect it from errors.

import React from 'react';
import ReactDOM from 'react-dom';
import ErrorBoundary from './ErrorBoundary';

function BuggyComponent() {
  if (Math.random() > 0.5) {
    throw new Error("Something went wrong!");
  }
  return <h1>Working!</h1>;
}

function App() {
  return (
    <div>
      <h1>Welcome to the App</h1>
      <ErrorBoundary>
        <BuggyComponent />
      </ErrorBoundary>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

Explanation

  • BuggyComponent: A simple component that randomly throws an error.
  • App: The main application component that wraps BuggyComponent with the ErrorBoundary.

When BuggyComponent throws an error, the Error Boundary catches it and displays "Something went wrong." instead of crashing the entire application.

Best Practices

  1. Contain Errors: Use Error Boundaries to contain errors in specific parts of your application without affecting the rest.
  2. Fallback UI: Provide a user-friendly fallback UI that explains what happened and possibly offers solutions or alternatives.
  3. Logging Errors: Log errors to an error reporting service like Sentry, Bugsnag, or Rollbar for monitoring and debugging.
  4. Avoid Catching Everything: Error Boundaries should not be used as a replacement for proper error handling in your codebase. They are meant to catch unexpected errors.
  5. Test Thoroughly: Test your Error Boundaries thoroughly to ensure they work as expected under different scenarios.

Advanced Usage

Updating State Based on Errors

You can update the state based on the type of error caught and render different fallback UIs accordingly.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorMessage: '' };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, errorMessage: error.message };
  }

  componentDidCatch(error, info) {
    console.error("An error occurred:", error);
    console.error("Component stack:", info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h1>Something went wrong.</h1>
          <p>{this.state.errorMessage}</p>
        </div>
      );
    }
    return this.props.children;
  }
}

Resetting Error State

You might want to reset the error state after a certain period or under specific conditions.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorMessage: '' };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, errorMessage: error.message };
  }

  componentDidCatch(error, info) {
    console.error("An error occurred:", error);
    console.error("Component stack:", info.componentStack);
  }

  resetErrorBoundary = () => {
    this.setState({ hasError: false, errorMessage: '' });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h1>Something went wrong.</h1>
          <p>{this.state.errorMessage}</p>
          <button onClick={this.resetErrorBoundary}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

Using with Higher-Order Components (HOCs)

You can create a higher-order component that wraps any component in an Error Boundary.

import React from 'react';
import ErrorBoundary from './ErrorBoundary';

function withErrorBoundary(WrappedComponent) {
  return function(props) {
    return (
      <ErrorBoundary>
        <WrappedComponent {...props} />
      </ErrorBoundary>
    );
  };
}

export default withErrorBoundary;

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import withErrorBoundary from './withErrorBoundary';

function BuggyComponent() {
  if (Math.random() > 0.5) {
    throw new Error("Something went wrong!");
  }
  return <h1>Working!</h1>;
}

const BuggyComponentWithBoundary = withErrorBoundary(BuggyComponent);

function App() {
  return (
    <div>
      <h1>Welcome to the App</h1>
      <BuggyComponentWithBoundary />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

Conclusion

Error Boundaries are a crucial feature in React for building robust applications that can gracefully handle errors. By understanding how to implement and use them, you can improve the reliability and user experience of your React applications. Remember to use them judiciously and combine them with other error handling techniques to create a comprehensive strategy for managing errors.

References

  • React Error Boundaries Documentation
  • Handling Errors in JavaScript

This tutorial provides a comprehensive guide to using Error Boundaries in React, complete with code examples and best practices. By following these guidelines, you can effectively manage errors in your applications and provide a better user experience.


PreviousProfiling React ApplicationsNext Handling Errors in Class Components

Recommended Gear

Profiling React ApplicationsHandling Errors in Class Components