Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Interview Essentials
  1. 1.Introduction to React & Basic Setup
  2. 2.JSX, Functional Components & Props
  3. 3.State Management with useState & useEffect
  4. 4.Conditional Rendering & List Management
  5. 5.Event Handling & Form Management
  6. 6.React Router for SPA Navigation
  7. 7.Context API for Global State
  8. 8.Working with Refs & the DOM
  9. 9.Advanced Component Patterns: HOCs & Render Props
  10. 10.Building Reusable Logic with Custom Hooks
  11. 11.Performance Optimization with Memoization
  12. 12.Error Boundaries for Robust UIs
  13. 13.Concurrent React & Suspense
  14. 14.Testing React Components with RTL
  15. 15.Advanced State Management (Overview)
React Interview Essentials
12

React · Lesson 12 of 15 · 3 min

Error Boundaries for Robust UIs

This is how you explain preventing a single component crash from taking down your entire app.

How an Error Boundary Catches a Crash

An unhandled JavaScript error during a render will unmount your entire React tree. An error boundary prevents this. It's a React component that catches errors in any of its children, logs them, and displays a fallback UI.

Think of it as a declarative try...catch for your component tree.

To become an error boundary, a class component must define at least one of these two lifecycle methods:

  1. static getDerivedStateFromError(error): React calls this after a child throws an error. Its only job is to return a state object (e.g., { hasError: true }). This triggers a re-render to show your fallback UI. You do not perform side effects here.

  2. componentDidCatch(error, errorInfo): React calls this after getDerivedStateFromError. Use it for side effects like logging the error and the errorInfo.componentStack to an external service. You don't typically use it to update state for the fallback UI.

The trap: Candidates often confuse the two methods. Remember the separation of concerns: getDerivedStateFromError for showing the fallback, componentDidCatch for logging. Also, know that because they use these lifecycle methods, error boundaries must be class components. Function components cannot be error boundaries.

Implementing a Resettable Error Boundary

A good error boundary does more than just show an error message. It should offer a way to recover. You can do this by passing a reset function to your fallback UI.

Here is a reusable, production-grade error boundary. It catches errors, allows for a custom fallback, and provides a reset mechanism.

import React, { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallbackRender: (props: { error: Error; reset: () => void }) => ReactNode;
}

interface State {
  error: Error | null;
}

class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // You would log the error to an error reporting service here.
    // For example: logErrorToMyService(error, errorInfo);
    console.error("ErrorBoundary caught an error", error, errorInfo);
  }

  reset = () => {
    this.setState({ error: null });
  };

  render() {
    const { error } = this.state;
    const { children, fallbackRender } = this.props;

    if (error) {
      // Render the fallback UI and pass it the error and a reset function.
      return fallbackRender({ error, reset: this.reset });
    }

    return children;
  }
}

export default ErrorBoundary;

To use the reset function effectively, you often need to combine it with changing the key on the child components. This forces React to unmount and remount them with fresh state.

What Error Boundaries Don't Catch

Knowing the limitations is as important as knowing the feature. Error boundaries do not catch errors in:

  • Event handlers: Errors inside an onClick or onChange happen outside the render lifecycle.
  • Asynchronous code: Errors in setTimeout, requestAnimationFrame, or Promise chains.
  • Server-side rendering: These need to be handled on the server.
  • The error boundary itself: It cannot catch an error thrown within its own render logic.

This is a common interview question. The answer for event handlers and async code is to use standard JavaScript try...catch or .catch() for promises.

const handleClick = async () => {
  try {
    const data = await riskyApiCall();
    // ...
  } catch (error) {
    // Handle error imperatively, e.g., show a toast notification.
    showToast('Failed to fetch data.');
  }
};

Where to Place Your Boundaries

Placement is a trade-off between user experience and fault isolation.

  • Too high: Wrapping your entire app in one boundary prevents a blank screen, but it also means any small error replaces the whole UI with a single fallback. The user loses all context.
  • Too granular: Wrapping every button is noisy and adds unnecessary complexity.

The best strategy is to place boundaries around logical, self-contained units of the UI. Good candidates include:

  • Individual widgets on a dashboard.
  • A complex data grid.
  • The main content area of a page, separate from the main navigation.
  • Any component that relies on third-party data or libraries that might be unstable.

When an error is thrown, React looks up the tree for the nearest error boundary. This allows you to contain failures gracefully.

In this diagram, an error in WidgetB is caught by EB. The rest of the application, including Sidebar and WidgetA, remains interactive. Without EB, the entire App would crash.

Try it

In 15 minutes, build a simple app with a component that has a button. When clicked, the component throws an error. Wrap this component in the ErrorBoundary from the example above. Implement a fallback UI that shows the error message and a "Try Again" button which resets the boundary. To make the reset work correctly, manage a key in the parent component that you increment on reset.

Next: We'll look at how to manage asynchronous operations and loading states declaratively with Concurrent React & Suspense.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Performance Optimization with Memoization

Next

Concurrent React & Suspense