Labs ICT
โญ Pro Login

Error Boundaries

Catching errors gracefully in your component tree.

What Are Error Boundaries?

Imagine a world where one broken component doesn't crash your entire app. That's what error boundaries provide. They're like safety nets that catch JavaScript errors in child components and display a fallback UI instead of crashing the whole tree.

Without error boundaries, a single error can unmount your entire component tree. Error boundaries let you gracefully handle errors, show meaningful messages, and keep the rest of your app running. They're like having a first aid kit for your components.

Catching Errors in Components

Error boundaries work similarly to try-catch blocks, but for React components. They catch errors during rendering, lifecycle methods, and constructors. When an error occurs, they stop the error from propagating and show a fallback UI instead.

You create an error boundary by defining a class component with a special lifecycle method. It's like setting up a security system that watches for problems and responds automatically.

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

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

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
Try it Yourself โ†’

Using componentDidCatch

The getDerivedStateFromError method updates state when an error occurs. But for logging errors to an error reporting service, you use componentDidCatch. It's like having a security camera that records what happened for later analysis.

You can use componentDidCatch to send error information to your monitoring service, like Sentry or LogRocket. This helps you understand what went wrong in production and fix it.

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

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

  componentDidCatch(error, errorInfo) {
    console.log("Error caught:", error);
    console.log("Component stack:", errorInfo.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
Try it Yourself โ†’

Fallback UI

The whole point of error boundaries is to show a helpful fallback UI when things go wrong. Instead of a blank screen or cryptic error message, you can show a friendly error page with a retry button or contact information.

Make your fallback UI helpful and informative. Tell users what happened, apologize for the inconvenience, and give them a way to recover. Good error handling is about maintaining trust even when things break.

๐Ÿงช Quick Quiz

What is an error boundary?