Table of contents
No headings in the article.
π Error handling is an essential aspect of building robust React applications. One powerful tool at our disposal is the Error Boundary component, which helps us gracefully handle and display errors in our UI.
π― What is an Error Boundary?
In React, an Error Boundary is a higher-order component that wraps around other components, catching any errors that occur during their rendering, lifecycle methods, or in their child components. By doing so, it prevents the entire application from crashing and allows us to present a fallback UI to the user.
import React, { useState } from 'react';
const ErrorBoundary = ({ children }) => {
const [hasError, setHasError] = useState(false);
const handleError = (error, errorInfo) => {
// Log the error or perform any necessary actions
console.error(error, errorInfo);
setHasError(true);
};
if (hasError) {
// Fallback UI when an error occurs
return <h1>Oops! Something went wrong.</h1>;
}
return (
<React.ErrorBoundary onError={handleError}>
{children}
</React.ErrorBoundary>
);
};
// Usage example
const MyComponent = ({ shouldThrowError }) => {
if (shouldThrowError) {
throw new Error('Error occurred!');
}
return <div>Normal rendering</div>;
};
const App = () => {
return (
<ErrorBoundary>
<MyComponent shouldThrowError={false} />
</ErrorBoundary>
);
};
export default App;
The
ErrorBoundary
component is a functional component that uses theuseState
hook to manage thehasError
state.The
handleError
function is responsible for logging the error and settinghasError
to true.If an error occurs (
hasError
is true), theErrorBoundary
component renders a fallback UI indicating that something went wrong.The
ErrorBoundary
component wraps itschildren
in theReact.ErrorBoundary
component provided by React, passing theonError
prop with thehandleError
function.The
MyComponent
component is a functional component that can throw an error based on theshouldThrowError
prop.Finally, the
App
component demonstrates the usage of theErrorBoundary
by wrapping theMyComponent
component with it.
π Embrace the power of Error Boundaries to provide a better user experience by preventing application crashes and gracefully handling errors. Level up your React skills and make your applications more robust today! πͺ
Thanks a lot for reading till the end π If you liked the article, please give likes and share it with your others.
Email: atul19251@gmail.com
LinkedIn: https://www.linkedin.com/in/atul-kumar-singh-673357102/