Error Handling with Error Boundary Hooks
Last Updated :
26 Feb, 2024
In the world of web development handling errors effectively is crucial for providing a seamless user experience. React one of the most popular JavaScript libraries provides a powerful feature known as Error Boundary Hooks that allows developers to handle errors in their applications.
In this article, we will explore how Error Boundary Hooks can be put to use to enhance error handling in React applications.
Understanding Error Handling and Error Boundaries Hooks
Error handling in React involves detecting and managing errors that occur during the rendering or updating of components. React provides a mechanism called Error Boundaries. React Error Boundary Hooks are class components that catch errors within their subtree and display a fallback UI instead of crashing the entire application. These components serve as crucial safeguards preventing user experience downtime due to unexpected errors. An Error Boundary Hook either uses componentDidCatch (for class components) or the error lifecycle method (for functional components) to catch errors within its subtree.
Syntax:
useErrorBoundary(WrappedComponent, FallbackUI = DefaultFallbackUI);
Steps to Create React Application:
Step 1: Create a new react app using the following command.
npx create-react-app my-react-app
Step 2: Navigate to the root directory of your project using the following command.
cd my-react-app
Example Code that Throws Error:
Javascript
import ComponentWithError
from "./ComponentwithError" ;
import React from "react" ;
const App = () => {
return <ComponentWithError />;
};
export default App;
|
Javascript
import React,
{
useEffect
} from "react" ;
const ComponentWithError = () => {
useEffect(() => {
throw new Error( "Something went wrong!" );
}, []);
return <div>
This code handles errors properly
</div>;
};
export default ComponentWithError;
|
Step to run the App:
npm start
Output:
Handling The Error Using Error-Boundary Hook:
Javascript
import ComponentwithError
from "./ComponentwithError" ;
import React from "react" ;
import { ErrorBoundary }
from "react-error-boundary" ;
const ErrorFallback =
({ error }) => (
<div role= "alert" >
<h2>
Something went wrong:
</h2>
<pre>
{error.message}
</pre>
</div>
);
const App = () => {
return (
<ErrorBoundary
FallbackComponent={ErrorFallback}>
<ComponentwithError />
</ErrorBoundary>
);
};
export default App;
|
Javascript
import React,
{
useEffect
} from "react" ;
const ComponentWithError = () => {
useEffect(() => {
throw new Error( "Something went wrong!" );
}, []);
return <div>This code handles errors properly</div>;
};
export default ComponentWithError;
|
Step to run the App:
npm start
Output:
Share your thoughts in the comments
Please Login to comment...