Blog>
Snippets

Handling Error States with Suspense

Provide an example of handling error states using an Error Boundary in conjunction with a Suspense boundary for a robust error handling strategy while fetching data.
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 };
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}
This is a React class-based component that functions as an Error Boundary. When an error occurs in its child components, it catches the error and changes its state to display a fallback UI, instead of crashing the app.
function MyComponent() {
  return (
    <ErrorBoundary>
      <React.Suspense fallback={<div>Loading...</div>}>
        <SomeComponent />
      </React.Suspense>
    </ErrorBoundary>
  );
}
Here, we wrap the SomeComponent with an ErrorBoundary and a Suspense component. Suspense handles the loading state, while the ErrorBoundary catches any errors that occur in the loading process and displays a graceful error message.