How does React Handle Errors in the Component Tree ?
Last Updated :
19 Apr, 2024
In the older versions of React (before v16), we do not have any feature to handle the React errors which were occurred in the components and these errors are used to corrupt the internal state of the React component.
Below are the methods to handle errors in the React component tree:
Using Error Boundaries
Error boundary in React is a class component that catches JavaScript errors that occur in the child component tree and displays a fallback UI instead of the component that is crashed. An error boundary is created by defining either of the life cycle methods static getDerivedStateFromError() or componentDidCatch() in the class component. You can create an error boundary component once and use it throughout the application.
NOTE: Error boundaries don't catch errors for Event handlers, Asynchronous code, Server side rendering, and Errors that occurred within the error boundary itself.
Example: The below code practically implements the error boundaries to handle errors in react component tree.
JavaScript
// App.js
import React from 'react';
import ErrorBoundary from
'./errorboundary';
function BrokenComponent() {
throw new Error
('Something bad happened!');
}
function App() {
return (
<ErrorBoundary>
<BrokenComponent />
<p>
This content will be
displayed normally.
</p>
</ErrorBoundary>
);
}
export default App;
JavaScript
// errorboundary.js
import React, { Component } from 'react';
export class ErrorBoundary extends
Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Error in component:", error);
console.error("Error info:", info);
}
render() {
if (this.state.hasError) {
return <h1>
Something went wrong.
</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Output :

Using Try/Catch with event Handlers
In React, error boundaries do not catch errors that occur inside event handlers, to catch such errors we use the regular JavaScript try/catch block with event handlers.
Syntax:
try {
changeButton();
}
catch (error) {
// Error Handler code
}
Example: The below code implements the try/catch block with event handlers to handle errors in react components.
JavaScript
// App.js
import React, { Component } from "react";
export class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { error: null };
this.handleButton = this.
handleButton.bind(this);
}
handleButton() {
try {
throw new Error
("Something bad happened!");
} catch (error) {
this.setState({ error });
console.log(error.message)
}
}
render() {
if (this.state.error) {
return <div>
<h1>
Caught an error.
</h1>
</div>
}
return <div>
<h2>
Click the below button to
<br /> catch the error.
</h2>
<button onClick={this.handleButton}>
Click Me
</button>
</div>
}
}
export default MyComponent;
Output:

Similar Reads
How To Handle Errors in React? 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 BoundariesError boundaries are a fe
5 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
Explain How Error Boundaries Propagate Errors in the Component Tree? React.js, a popular JavaScript library for building user interfaces, affords a robust mechanism for handling errors gracefully within component trees. This mechanism is referred to as "error boundaries." Error limitations are React components that capture JavaScript mistakes everywhere in their baby
4 min read
Hook error handling doesn't catch errors in ReactJS In this article, we will see one of the common issues faced by ReactJS developers is the Hook error handling problem. This issue occurs when an error is thrown inside a Hook, but it is not caught and handled properly. As a result, the error goes unaddressed and can cause unexpected behavior in the a
2 min read
How to conditionally render components in ReactJS ? React is a declarative, efficient, and flexible JavaScript library for building user interfaces. Itâs âVâ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.PrerequisitesNodeJS or NPMReact JSReact
3 min read