How to create an error boundary in React?

In React, you can create an error boundary component by creating a class component that implements static getDerivedStateFromError() and componentDidCatch() lifecycle methods. These methods are used to catch and handle any errors that occur within the component or its descendants.

Here's an example of how to create an error boundary component in React:

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) { // You can log the error to an error reporting service console.error(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } export default ErrorBoundary;

To use the error boundary component, simply wrap the components you want to catch errors for with the ErrorBoundary component:

<ErrorBoundary> <YourComponent /> </ErrorBoundary>

Now, any errors that occur within the component or its descendants will be caught by the ErrorBoundary component and the "Something went wrong." message will be displayed instead of crashing the entire application.