0
0
ReactHow-ToBeginner · 4 min read

How to Create Error Boundary in React: Simple Guide

In React, create an ErrorBoundary by defining a component that uses the componentDidCatch lifecycle method or the useErrorBoundary hook from libraries. The boundary catches errors in child components and shows a fallback UI instead of crashing the whole app.
📐

Syntax

An error boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI.

It requires defining static getDerivedStateFromError(error) to update state on error and componentDidCatch(error, info) to log the error.

jsx
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 caught:', error, errorInfo);
  }

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

Example

This example shows a simple ErrorBoundary component wrapping a child component that throws an error. When the error happens, the boundary catches it and displays a fallback message instead of crashing the app.

jsx
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 caught:', error, errorInfo);
  }

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

function BuggyComponent() {
  throw new Error('I crashed!');
  // return <div>This will not render.</div>;
}

export default function App() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  );
}
Output
Something went wrong.
⚠️

Common Pitfalls

  • Not wrapping components with the error boundary, so errors still crash the app.
  • Using error boundaries to catch errors in event handlers or async code, which they do not catch.
  • Forgetting to update state in getDerivedStateFromError, so fallback UI never shows.
  • Logging errors only in componentDidCatch but not updating UI state.
jsx
/* Wrong: No state update, fallback UI won't show */
class WrongBoundary extends React.Component {
  componentDidCatch(error, info) {
    console.error(error);
  }
  render() {
    return this.props.children;
  }
}

/* Right: Update state to show fallback UI */
class RightBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error(error);
  }
  render() {
    if (this.state.hasError) {
      return <h1>Oops! Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
📊

Quick Reference

Error Boundary Key Points:

  • Wrap components that may throw errors.
  • Implement getDerivedStateFromError to update UI state.
  • Use componentDidCatch to log errors.
  • Does not catch errors in event handlers or async code.

Key Takeaways

Create an error boundary by defining a class component with getDerivedStateFromError and componentDidCatch methods.
Wrap child components with the error boundary to catch rendering errors and show fallback UI.
Error boundaries do not catch errors in event handlers or asynchronous code.
Always update state in getDerivedStateFromError to trigger fallback UI rendering.
Use componentDidCatch to log error details for debugging.