How To Handle Errors in React?
Last Updated :
12 Feb, 2025
Handling errors in React is essential for creating a smooth user experience and ensuring the stability of your application. Whether you're working with functional or class components, React provides different mechanisms to handle errors effectively.
1. Using Error Boundaries
Error boundaries are a feature in React that allows components to catch JavaScript errors anywhere in their component tree and log those errors, display a fallback UI, or take other actions.
To create an error boundary, a component needs to define static
getDerivedStateFromError and lifecycle componentDidCatch methods.
JavaScript
//App.js
import React from "react";
import ErrorBoundary from "./Components/ErrorBoundary";
import BuggyComponent from "./Components/BuggyComponent";
const App = () => {
return (
<div style={{ textAlign: "center", marginTop: "30px" }}>
<h1>React Error Boundaries Example</h1>
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
</div>
);
};
export default App;
JavaScript
// ErrorBoundary.js
import React, { Component } from "react";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error("Error caught by Error Boundary:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h2 style={{ color: "red", textAlign: "center" }}>
Oops! Something went wrong. 😢</h2>;
}
return this.props.children;
}
}
export default ErrorBoundary;
JavaScript
// BuggyComponent.js
import React, { useState } from "react";
const BuggyComponent = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
if (count >= 2) {
throw new Error("You clicked too many times! 🚨");
}
setCount(count + 1);
};
return (
<div style={{ marginLeft: "20px", marginTop: "20px" }}>
<div style={{ display: "flex", flexDirection: "column",
alignItems: "flex-start", gap: "20px" }}>
<h2>Click the button, but not too much! 😁</h2>
<button onClick={handleClick} style={{ padding: "10px",
fontSize: "16px" }}>
Click Me ({count})
</button>
</div>
</div>
);
};
export default BuggyComponent;
Output
Using Error BoundariesIn this code
- ErrorBoundary.js: Catches errors in child components and shows a fallback UI.
- BuggyComponent.js: Throws an error if clicked more than 3 times.
- App.js: Wraps BuggyComponent in ErrorBoundary to prevent app crashes.
2. Using try-catch in Event Handlers
When dealing with asynchronous operations, such as fetching data or handling events, you can use the standard JavaScript try-catch block to catch errors and handle them gracefully.
JavaScript
//App.js
import React from "react";
import ErrorHandlingComponent from "./Components/ErrorHandlingComponent";
const App = () => {
return (
<div style={{ textAlign: "center", marginTop: "30px" }}>
<h1>React Error Handling Example</h1>
<ErrorHandlingComponent />
</div>
);
};
export default App;
JavaScript
// ErrorHandlingComponent
import React, { useState } from "react";
const ErrorHandlingComponent = () => {
const [message, setMessage] = useState("");
const handleClick = () => {
try {
const randomNum = Math.random();
if (randomNum > 0.5) {
throw new Error("You can't click twice!");
}
setMessage("Operation successful ✅");
} catch (error) {
setMessage(`Error: ${error.message} ❌`);
}
};
return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h2>Try-Catch in React Event Handler</h2>
<button onClick={handleClick}
style={{ padding: "10px", fontSize: "16px" }}>
Click Me
</button>
<p>{message}</p>
</div>
);
};
export default ErrorHandlingComponent;
Output
try-catch in Event HandlersIn this code
- ErrorHandlingComponent: Handles button clicks and errors.
- handleClick(): Throws "You can't click twice!" if a random number > 0.5.
- Uses try-catch: Catches errors and updates the message.
- Renders UI: Displays success or error message based on clicks.
3. Handling Errors in API Calls
API calls are a common source of errors in React apps. You can manage these errors gracefully by showing a loading state and an error message.
JavaScript
//App.js
import React from "react";
import ApiComponent from "./components/ApiComponent";
const App = () => {
return (
<div>
<h1 style={{ textAlign: "center" }}>React API Error Handling Example</h1>
<ApiComponent />
</div>
);
};
export default App;
JavaScript
//ApiService.js
export const fetchData = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/invalid-url");
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
throw new Error(`Failed to fetch data: ${error.message}`);
}
};
JavaScript
//ApiComponent.js
import React, { useState } from "react";
import { fetchData } from "../services/ApiService";
const ApiComponent = () => {
const [data, setData] = useState(null);
const [error, setError] = useState("");
const handleFetch = async () => {
try {
setError("");
setData(null);
const result = await fetchData();
setData(result);
} catch (error) {
setError(error.message);
}
};
return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h2>API Error Handling in React</h2>
<button onClick={handleFetch} style={{ padding: "10px", fontSize: "16px" }}>
Fetch Data
</button>
{error && <p style={{ color: "red", fontWeight: "bold" }}>❌ {error}</p>}
{data && (
<div>
<h3>✅ Data Fetched Successfully:</h3>
<p><strong>Title:</strong> {data.title}</p>
</div>
)}
</div>
);
};
export default ApiComponent;
Output
Handling Errors in API CallsIn this code
- ApiService.js: Fetches data, throws an error if API fails.
- ApiComponent.js: Calls API, shows data on success, error in red on failure.
- App.js: Loads ApiComponent, ensures smooth error handling.
Conclusion
Error handling in React is essential to prevent application crashes and enhance user experience. The best approach depends on the type of error:
- Error Boundaries for component-level crashes.
- Try-catch blocks in event handlers for user interactions.
- Try-catch in API calls for network request failures.
By implementing these strategies, you can build robust React applications that gracefully handle errors and provide a better user experience.
Similar Reads
How to handle forms in React ? In React, Form handling is one of the basic and important concepts that every developer should learn about. Forms are used to collect the data so that we can use the data for various purposes. This article, lets us understand form handling in React along with examples.Prerequisites:JSXReactuseStateF
6 min read
How to Handle Errors in JavaScript? In JavaScript Error Handling is used to find the errors in the code so, that the coder can find the particular issue to resolve it. Here are the different approaches to handle errors in JavaScript1. Using try catch and finally statementThe try, catch, and finally blocks are used for error handling.
4 min read
How to Handle Errors in Node.js ? Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior
4 min read
How to Handle Errors in React Redux applications? To handle errors in Redux applications, use try-catch blocks in your asynchronous action creators to catch errors from API calls or other async operations. Dispatch actions to update the Redux state with error information, which can then be displayed to the user in the UI using components like error
4 min read
How are events handled in React? Modern webpages rely on user interactions, triggering events like clicks or keypresses. React facilitates event handling with built-in methods, allowing developers to create listeners for dynamic interfaces and responses. JavaScript events, inherent to the DOM, use bubbling propagation by default, m
2 min read