πŸš€ Mastering Error Boundaries in React! πŸš€

πŸš€ Mastering Error Boundaries in React! πŸš€

Table of contents

No heading

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 the useState hook to manage the hasError state.

  • The handleError function is responsible for logging the error and setting hasError to true.

  • If an error occurs (hasError is true), the ErrorBoundary component renders a fallback UI indicating that something went wrong.

  • The ErrorBoundary component wraps its children in the React.ErrorBoundary component provided by React, passing the onError prop with the handleError function.

  • The MyComponent component is a functional component that can throw an error based on the shouldThrowError prop.

  • Finally, the App component demonstrates the usage of the ErrorBoundary by wrapping the MyComponent 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/

Web: https://iamatul.netlify.app/

Did you find this article valuable?

Support Dev Station by becoming a sponsor. Any amount is appreciated!

Β