How do you handle errors and exceptions in a React application?

Errors and exceptions in a React application can be handled using a combination of the JavaScript try and catch statements, as well as React's built-in error boundary feature.

  • Within a component, you can use the try and catch statements to catch and handle any errors that occur within the component's render method or lifecycle methods.
  • You can also use React's error boundary feature to create a component that catches errors that occur within its child components. This allows you to display a fallback UI or log the error, rather than letting the error propagate and potentially crash the whole application.

Example of error boundary component:

class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can also log the error to an error reporting service logErrorToMyService(error, errorInfo); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } }

And then use it as a wrapper component:
<ErrorBoundary> <MyComponent /> </ErrorBoundary>

This way, if an error occurs within MyComponent, the error will be caught by the error boundary and handled accordingly.