What Is Error Boundaries In React?
Error Boundaries are special components in React that catch JavaScript errors anywhere in the component tree and preventing the whole app from crashing.
Imagine you are building a website, and one small component breaks like a broken image, so in this case not your entire app showing error or black screen, only image section showing fallback UI error like “Oops! Something went wrong.” using Error Boundary.
React Error Boundaries can automatically catch certain kinds of errors that happen after your app has started running (runtime errors).
If a component crashes during generating JSX, so error boundaries will catch it.
Student using learning app and if any lesson has a crashes and bug, so without Error Boundaries the whole app crashes.
With Error Boundaries React catch the problem and show a message in only crashes part.
Error Boundaries can catch special functions of lifecycle methods like componentDidMount, componentDidUpdate, etc. If error happens inside them so Error Boundaries will catch it.
Error Boundaries In React cannot catch
Error Boundaries in react can not catch:
- Event handlers : if a button is clicked and something inside the onClick function goes wrong, Error Boundary won’t catch it. If a button is clicked and in button onClick function give bugs and error so Error Boundaries won’t catch it.
- Asynchronous code : If you are using setTimeout, Fetch() or promises, and if error happens inside them so Error Boundaries can’t see that. you have to handle those errors by try…catch or .catch() methods.
- Server-side rendering (SSR) : If you are rendering your app on the server (not in browser), So Error Boundaries don’t work there.
Syntax of Error Boundaries
// Simple & Unique Error Boundary Syntax
import React from 'react';
class SafeGuard extends React.Component {
constructor(props) {
super(props);
this.state = { problem: false };
}
static getDerivedStateFromError() {
return { problem: true };
}
componentDidCatch(error, info) {
// You can log error here or send to server
console.warn("App Error:", error, info);
}
render() {
if (this.state.problem) {
return <h3>Oops! Something went wrong.</h3>;
}
return this.props.children;
}
}
export default SafeGuard;
Meaning Of Above Code:
class SafeGuard extends React.Component {
Meaning: First create a SafeGuard class componet. It extends React.Component, meaning it inherits all the features of a React component
constructor(props) {
super(props);
this.state = { problem: false };
}
- The constructor runs when the component is first created.
- We call super(props) to access this.props inside the constructor.
- this.state = { problem: false } means: we assume there is no error (problem: false).
static getDerivedStateFromError() {
return { problem: true };
}
- When a child component throws error so build-in react component is automaically called.
- That update tells React to show fallback message rather than breaking the entire app.
componentDidCatch(error, info) {
console.warn("App Error:", error, info);
}
- This method help us to understand what went wrong.
- error = what went wrong.
- info = which part of the component failed.
- We are logging it to the console for debugging.
render() {
if (this.state.problem) {
return <h3>Oops! Something went wrong.</h3>;
}
return this.props.children;
}
- render() is what the user see on screen.
- If problem is true, so it show a simple error message.
- If there is no error, it renders the normal child components (this.props.children).
Part | What it Does |
---|---|
constructor | Initialize the component state. |
getDerivedStateFromError | Triggers when error occurs, changes state. |
componentDidCatch | Capture error info (for logging/debugging). |
render | Show error message |
SafeGuard | Custom Error Boundary component name. |
Real-life Example: Smart Thermometer App
In this small UI we building smart thermometer that show the temperature of different rooms. But sometime the sensor of the room may be broken. we are use the Error Boundaries to handle this situation.
Error Boundary Component (SafeGuard)
import React from 'react';
class SafeGuard extends React.Component {
constructor(props) {
super(props);
this.state = { hasIssue: false };
}
static getDerivedStateFromError() {
return { hasIssue: true };
}
componentDidCatch(error, info) {
console.log("Thermometer error captured:", error, info);
}
render() {
if (this.state.hasIssue) {
return <div style={{ color: 'crimson' }}>Sensor not responding. Please try again later.</div>;
}
return this.props.children;
}
}
export default SafeGuard;
In this code:
- hasIssue is a flag to detect if something went wrong.
- If any error happens in to the child component, so getDerivedStateFromError update the state.
- componentDidCatch() logs the error in the browser console.
- Only a red warning message will show if something will happen.
- If no error occur, it renders to the the child component.
Room Temperature Component (That Might Fail)
function RoomTemperature({ temp }) {
if (temp === undefined || temp === null) {
throw new Error("Invalid temperature data");
}
return <h3>Room Temperature: {temp}°C</h3>;
}
- If the temperature data is missing, so the component throws an error.
- That error is caught by the SafeGuard.
- Otherwise, it simply shows the room’s temperature.
App Component
import React from 'react';
import SafeGuard from './SafeGuard';
function HomeThermometerApp() {
const sensorData = {
livingRoom: 24,
kitchen: null, // Error: faulty sensor
bedroom: 22
};
return (
<div>
<h2>Smart Home Thermometer</h2>
<SafeGuard>
<RoomTemperature temp={sensorData.livingRoom} />
</SafeGuard>
<SafeGuard>
<RoomTemperature temp={sensorData.kitchen} />
</SafeGuard>
<SafeGuard>
<RoomTemperature temp={sensorData.bedroom} />
</SafeGuard>
</div>
);
}
export default HomeThermometerApp;
- sensorData contains three rooms and their current temperature.
- The kitchen sensor has null, meaning it is not sending data.
- We wrap each room’s temperature component with SafeGuard to catch any specific error easily.
- If one room’s sensor fail, it doesn’t impact to others rooms.
- Only specific section will display error message.