What Are React Error Boundaries? Complete Example Tutorial

What Are Error Boundaries?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the app.


Creating an 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, info) {
    console.log("Error:", error, "Info:", info);
  }

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

Using the Error Boundary

function BuggyComponent() {
  throw new Error("I crashed!");
}

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

✅ App displays fallback UI instead of crashing.


Key Points

  • Only class components can be error boundaries
  • Catch errors in child components, lifecycle methods, and render
  • Do not catch errors in event handlers
  • Use multiple boundaries for better isolation

Conclusion

Error boundaries make React apps resilient by handling unexpected errors gracefully, improving user experience and stability.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *