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 whole app.
๐น Key Points:
โ
They only catch errors in class components (not functional components or event handlers).
โ
They do not catch errors in async code, event handlers, or server-side rendering (SSR).
Create an Error Boundary Component (src/ErrorBoundary.js
)
Since Error Boundaries must be class components, create a new file ErrorBoundary.js
:
import React, { Component } from "react"; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state to show fallback UI return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error("Caught an error:", error, errorInfo); } render() { if (this.state.hasError) { return ( <div style={{ textAlign: "center", marginTop: "50px", color: "red" }}> <h2>๐จ Oops! Something went wrong.</h2> <p>Try refreshing the page or contact support.</p> </div> ); } return this.props.children; } } export default ErrorBoundary;
Use the Error Boundary in src/App.js
Wrap error-prone components with <ErrorBoundary>
:
import React, { useState } from "react"; import ErrorBoundary from "./ErrorBoundary"; const BuggyComponent = () => { const [throwError, setThrowError] = useState(false); if (throwError) { throw new Error("Something went wrong!"); } return ( <div> <h2>Click the button to trigger an error</h2> <button onClick={() => setThrowError(true)}>Break the App ๐จ</button> </div> ); }; function App() { return ( <div style={{ textAlign: "center", marginTop: "50px" }}> <h1>โ ๏ธ React Error Boundaries</h1> <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> </div> ); } export default App;
Why Use Error Boundaries?
โ Prevent full app crashes โ only the failing component is affected.
โ Provide a user-friendly error message instead of a blank screen.
โ Log errors to services like Sentry or Firebase for debugging.