🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

Error Handling with Error Boundaries

AI & DATA SCIENCE // error-boundaries

An Error Boundary is a class component that catches JavaScript errors thrown anywhere in its child component tree during rendering, displaying a fallback UI instead of crashing the entire application.

Syntax

class ErrorBoundary extends React.Component {
  static getDerivedStateFromError(error) { return { hasError: true }; }
  componentDidCatch(error, info) { /* log error */ }
  render() { return this.state.hasError ? <Fallback /> : this.props.children; }
}

Deep Dive Course

Without an Error Boundary, an uncaught error thrown during rendering anywhere in a component tree unmounts that entire tree, potentially crashing the whole visible application down to a blank white screen — wrapping a section of the tree in an Error Boundary catches such errors, using the static getDerivedStateFromError() lifecycle method to update state and render a fallback UI instead, and componentDidCatch() to log the error details for debugging. Error Boundaries can currently only be implemented as class components, since there's no functional-component/hooks equivalent of these specific error-catching lifecycle methods, and they only catch errors thrown during rendering, in lifecycle methods, and in constructors of the components below them, not errors inside event handlers, asynchronous code, or server-side rendering.

1Understanding Error Handling with Error Boundaries

Without an Error Boundary, an uncaught error thrown during rendering anywhere in a component tree unmounts that entire tree, potentially crashing the whole visible application down to a blank white screen — wrapping a section of the tree in an Error Boundary catches such errors, using the static getDerivedStateFromError() lifecycle method to update state and render a fallback UI instead, and componentDidCatch() to log the error details for debugging. Error Boundaries can currently only be implemented as class components, since there's no functional-component/hooks equivalent of these specific error-catching lifecycle methods, and they only catch errors thrown during rendering, in lifecycle methods, and in constructors of the components below them, not errors inside event handlers, asynchronous code, or server-side rendering.

💡

Error Boundaries do NOT catch errors thrown inside event handlers — a try/catch block around the specific risky logic in an event handler, or the handler's own error state, is still needed for those cases, since Error Boundaries are strictly about errors during rendering.

editor.html
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error('Caught an error:', error);
  }
  render() {
    if (this.state.hasError) return <h2>Something went wrong.</h2>;
    return this.props.children;
  }
}
localhost:3000

2Practical Example

Here is a real-world application of Error Handling with Error Boundaries showing how it is used in production React code.

editor.html
function BuggyComponent() {
  throw new Error('Oops!');
}

function App() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  );
}
localhost:3000

3Best Practices

Follow these guidelines when working with Error Handling with Error Boundaries:

1. Wrap distinct, independent sections of an application, like a sidebar widget or a specific feature area, in their own Error Boundary, so an error in one section doesn't take down the entire page

2. Use componentDidCatch() to log caught errors to an error-tracking service, so rendering crashes are visible and diagnosable in production

3. Handle errors inside event handlers with a regular try/catch block, since Error Boundaries specifically don't catch those — they only catch errors during rendering

⚠️

Tip: Error Boundaries do NOT catch errors thrown inside event handlers — a try/catch block around the specific risky logic in an event handler, or the handler's own error state, is still needed for those cases, since Error Boundaries are strictly about errors during rendering.

editor.html
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error('Caught an error:', error);
  }
  render() {
    if (this.state.hasError) return <h2>Something went wrong.</h2>;
    return this.props.children;
  }
}
localhost:3000

Examples

Example 01Basic Usage
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error('Caught an error:', error);
  }
  render() {
    if (this.state.hasError) return <h2>Something went wrong.</h2>;
    return this.props.children;
  }
}
Example 02Advanced Example
function BuggyComponent() {
  throw new Error('Oops!');
}

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

Best Practices

  • Wrap distinct, independent sections of an application, like a sidebar widget or a specific feature area, in their own Error Boundary, so an error in one section doesn't take down the entire page
  • Use componentDidCatch() to log caught errors to an error-tracking service, so rendering crashes are visible and diagnosable in production
  • Handle errors inside event handlers with a regular try/catch block, since Error Boundaries specifically don't catch those — they only catch errors during rendering

Interview Question

Why can't an Error Boundary be written as a functional component with hooks, unlike most other modern React components?

Hint: Think about what specific lifecycle methods an Error Boundary relies on, and whether those have a direct hooks equivalent.

Error Boundaries specifically rely on two class-component lifecycle methods, the static getDerivedStateFromError(), which updates state in response to a descendant throwing during render, and componentDidCatch(), which receives the caught error and additional info for logging purposes — as of the current React API, there's no hook that provides this exact same catch-an-error-thrown-by-a-descendant-during-rendering capability, since hooks are fundamentally built around a component managing and reacting to its own state and effects, not intercepting errors thrown by its children's rendering. Until React introduces an equivalent hook, if it ever does, Error Boundaries remain one of the few remaining cases where a class component is still genuinely necessary rather than just a legacy pattern, which is why they're commonly implemented once, as a small reusable class component, and reused throughout an otherwise fully functional-component-based codebase.

Exercises

MediumPractice using Error Handling with Error Boundaries in a real scenario.
View Solution
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error('Caught an error:', error);
  }
  render() {
    if (this.state.hasError) return <h2>Something went wrong.</h2>;
    return this.props.children;
  }
}

Frequently Asked Questions

Why can't an Error Boundary be written as a functional component with hooks, unlike most other modern React components?

Error Boundaries specifically rely on two class-component lifecycle methods, the static getDerivedStateFromError(), which updates state in response to a descendant throwing during render, and componentDidCatch(), which receives the caught error and additional info for logging purposes — as of the current React API, there's no hook that provides this exact same catch-an-error-thrown-by-a-descendant-during-rendering capability, since hooks are fundamentally built around a component managing and reacting to its own state and effects, not intercepting errors thrown by its children's rendering. Until React introduces an equivalent hook, if it ever does, Error Boundaries remain one of the few remaining cases where a class component is still genuinely necessary rather than just a legacy pattern, which is why they're commonly implemented once, as a small reusable class component, and reused throughout an otherwise fully functional-component-based codebase.

Related Functions

suspenselazy-loadingcomponentdidmount