Error Boundaries in React: Catching Errors with Class Components

⚛️ Top 150 React Interview Questions – 38/150 📌 Topic: Error Boundaries 🔹 WHAT is it? An Error Boundary is a special React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and shows a fallback UI instead of crashing the entire app (White Screen of Death). 🔹 WHY is it designed this way? Before React 16, an error inside a component could break the entire application. Graceful Degradation: Only the failed part (like a widget or sidebar) stops working, while the rest of the app stays alive. Better User Experience: Users see a clean “Something went wrong” message instead of a blank screen. Error Reporting: Central place to log errors using tools like Sentry or LogRocket. 🔹 HOW do you do it? (The Implementation) 👉 Error Boundaries must be Class Components (no Hook alternative yet). class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log("Logged Error:", error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } Usage: <ErrorBoundary> <MyProfile /> </ErrorBoundary> 🔹 WHERE are the best practices? When to Use: Wrap top-level routes or heavy components like charts, ads, or third-party widgets. Limitations: Error Boundaries do NOT catch: Event handler errors Async code (setTimeout, promises) Server-side rendering errors Granularity: Avoid one global boundary. Use multiple boundaries so unaffected parts remain interactive. 📝 Summary for your notes: An Error Boundary is like a Circuit Breaker ⚡ If one appliance (component) fails, only that section shuts down — the rest of the house (app) keeps running. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories