React js Error Boundaries Practice Questions with Solutions

Introduction

Error Boundaries are React components that catch errors during rendering and related React lifecycle work in a part of the component tree. Instead of allowing an error to break the entire user interface, an Error Boundary can display a fallback UI for the affected section. Error Boundaries are especially useful in larger applications where one broken component should not necessarily make the whole interface unusable. In this chapter, we will solve practical questions about Error Boundaries, fallback UI, errors, and recovery. React js Error Boundaries practice questions with solutions to help you understand the concepts.

1. What is an Error Boundary in React (React Error Boundary)?

Answer:

An Error Boundary is a React component that catches certain errors thrown by components in its child tree during rendering and displays a fallback UI instead of allowing that part of the UI to crash.

A common structure is:

<ErrorBoundary>
  <Dashboard />
</ErrorBoundary>

If Dashboard or a component below it throws an error during rendering, the Error Boundary can display an alternative UI.

For example:

Dashboard
   ↓
Component Error
   ↓
Error Boundary
   ↓
"Something went wrong"

Error Boundaries are useful for making applications more resilient to unexpected rendering errors.


2. Which Errors Can Error Boundaries Catch?

Answer:

Error Boundaries can catch errors that occur in certain React rendering-related work in their descendant tree.

For example:

function Profile() {
  throw new Error("Profile failed");

  return <h2>Profile</h2>;
}

If Profile is inside an Error Boundary, the boundary can display its fallback UI.

Error Boundaries are designed primarily for errors during:

  • Rendering
  • Constructors of class components
  • Certain lifecycle methods
  • Rendering of descendant components

They help prevent a rendering error in one part of the application from taking down the entire visible UI.


3. Can a Function Component Directly Become an Error Boundary (React Error Boundary)?

Answer:

A regular function component cannot simply become an Error Boundary by adding a special function.

The traditional React Error Boundary API uses a class component with methods such as:

static getDerivedStateFromError()

and:

componentDidCatch()

Example:

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError(error) {
    return {
      hasError: true
    };
  }

  componentDidCatch(error, errorInfo) {
    console.error(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong.</h2>;
    }

    return this.props.children;
  }
}

You can then use it around a component tree:

<ErrorBoundary>
  <Dashboard />
</ErrorBoundary>

Third-party libraries can also provide function-component-friendly APIs for error boundaries.


4. How Do You Create a Basic Error Boundary?

Answer:

A basic Error Boundary can be created using a class component.(React Error Boundary)

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError(error) {
    return {
      hasError: true
    };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Error:", error);
    console.error("Error Info:", errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong.</h2>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Then use it like this:

function App() {
  return (
    <ErrorBoundary>
      <Dashboard />
    </ErrorBoundary>
  );
}

If a descendant throws a supported rendering error, the boundary switches to:

Something went wrong.


5. What is getDerivedStateFromError() Used For?

Answer:

getDerivedStateFromError() is a static class method used to update the Error Boundary’s state after an error is thrown by a descendant.

Example:

static getDerivedStateFromError(error) {
  return {
    hasError: true
  };
}

The returned state can be used to display fallback UI:

render() {
  if (this.state.hasError) {
    return <h2>Something went wrong.</h2>;
  }

  return this.props.children;
}

In simple terms:

Error occurs
     ↓
getDerivedStateFromError()
     ↓
State changes
     ↓
Fallback UI is rendered

The method is intended for updating the UI state of the boundary.


6. What is componentDidCatch() Used For?

Answer:

componentDidCatch() is used for handling error-related side effects, such as logging an error.

Example:

componentDidCatch(error, errorInfo) {
  console.error("Error:", error);
  console.error("Component information:", errorInfo);
}

It can be useful for sending error information to an error monitoring service.

A common Error Boundary can therefore use:

static getDerivedStateFromError(error) {
  return { hasError: true };
}

componentDidCatch(error, errorInfo) {
  console.error(error, errorInfo);
}

The first method helps update the UI, while the second is useful for side effects such as logging.


7. Do Error Boundaries Catch Errors in Event Handlers?

Answer:

No. Error Boundaries do not automatically catch errors thrown inside event handlers.

For example:

function Button() {
  function handleClick() {
    throw new Error("Button error");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

The error from the event handler should be handled explicitly if needed:

function handleClick() {
  try {
    throw new Error("Button error");
  } catch (error) {
    console.error(error);
  }
}

Similarly, Error Boundaries are not a general-purpose replacement for handling errors from arbitrary asynchronous code.

For API requests, for example, use normal error handling:

try {
  const response = await fetch("/api/users");

  if (!response.ok) {
    throw new Error("Request failed");
  }
} catch (error) {
  console.error(error);
}


8. Can Error Boundaries Handle Errors From Lazy-Loaded Components?

Answer:

Yes. An Error Boundary can be placed around a lazy-loaded component to handle errors that occur if the lazy component or its loading process fails.

Example:

import { lazy, Suspense } from "react";

const Dashboard = lazy(() => import("./Dashboard"));

function App() {
  return (
    <ErrorBoundary>
      <Suspense fallback={<p>Loading Dashboard...</p>}>
        <Dashboard />
      </Suspense>
    </ErrorBoundary>
  );
}

Here:

Suspense
   ↓
Handles loading state

Error Boundary
   ↓
Handles supported errors

This gives the user both a loading state and an error fallback.

Suspense and Error Boundaries have different responsibilities and can be used together.


9. Can You Place Multiple Error Boundaries in an Application?

Answer:

Yes. Multiple Error Boundaries can be placed at different levels of an application.

For example:

function App() {
  return (
    <div>
      <ErrorBoundary>
        <Header />
      </ErrorBoundary>

      <ErrorBoundary>
        <Dashboard />
      </ErrorBoundary>

      <ErrorBoundary>
        <Footer />
      </ErrorBoundary>
    </div>
  );
}

This allows different sections to have independent error handling.

For example, if the Dashboard fails, the Header and Footer can potentially continue working.

A common strategy is to place boundaries around meaningful sections such as:

  • Dashboard
  • Navigation
  • Reports
  • User profile
  • Individual large features

The right placement depends on the application’s requirements.


10. Create a Practical Error Boundary With a Fallback UI

Answer:

Here is a practical Error Boundary that displays a user-friendly fallback message.

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError(error) {
    return {
      hasError: true
    };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Application Error:", error);
    console.error("Error Information:", errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h2>Something went wrong.</h2>
          <p>Please try again later.</p>
        </div>
      );
    }

    return this.props.children;
  }
}

function ProblemComponent() {
  throw new Error("Something failed!");
}

function App() {
  return (
    <ErrorBoundary>
      <ProblemComponent />
    </ErrorBoundary>
  );
}

export default App;

When ProblemComponent throws an error during rendering, the Error Boundary displays:

Something went wrong.
Please try again later.

The application can also log the error using:

componentDidCatch(error, errorInfo)

In a production application, error information can be sent to an appropriate monitoring system.

Key Takeaways

  • Error Boundaries help prevent rendering errors from breaking the entire React UI.
  • Traditional React Error Boundaries use class components.
  • getDerivedStateFromError() can update state for fallback UI.
  • componentDidCatch() can be used for logging and other side effects.
  • Error Boundaries catch supported errors in their descendant rendering tree.
  • They do not automatically catch errors from event handlers.
  • API and asynchronous errors should usually be handled with try/catch and appropriate application logic.
  • Error Boundaries can be combined with Suspense.
  • Multiple Error Boundaries can isolate different application sections.
  • A good fallback UI should clearly tell users that something went wrong.
  • Error Boundaries are not a replacement for normal error handling.
  • Error monitoring can help developers identify production problems.

FAQs

1. What is an Error Boundary in React (React Error Boundary)?

An Error Boundary is a React component that catches certain errors in its descendant rendering tree and displays fallback UI instead of allowing the affected section to fail completely.

2. Are Error Boundaries available as normal function components?

The built-in Error Boundary API is based on class components. Function components can use Error Boundary libraries that provide alternative APIs.

3. What does getDerivedStateFromError() do?

It allows an Error Boundary to update its state after catching a descendant error so that fallback UI can be rendered.

4. What does componentDidCatch() do?

componentDidCatch() is used for side effects after an error has been caught, such as logging error details or reporting them to an error monitoring system.

5. Do Error Boundaries catch event-handler errors?

No. Errors thrown inside event handlers are not automatically caught by Error Boundaries. They should be handled in the event-handler logic when appropriate.

6. Can Error Boundaries work with Suspense?

Yes. They can be combined so that Suspense handles loading states while the react Error Boundary handles supported errors.

7. Why should an application use multiple Error Boundaries?

Multiple boundaries can isolate different parts of the application. If one feature fails, other independent sections may remain usable.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top