Blog>
Snippets

Lazy Loaded Components with Error Boundaries

Demonstrate how to use Error Boundaries with React.lazy and Suspense to handle errors during code-splitting and dynamic imports.
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; 
  }
}
This code defines an ErrorBoundary class component that you can use to wrap around your lazy-loaded components. If there's an error while loading the component, it will display a fallback UI ('Something went wrong.' message) instead of crashing the app.
const LazyComponent = React.lazy(() => import('./LazyComponent'));

// ... inside your component render or functional component
<ErrorBoundary>
  <React.Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
  </React.Suspense>
</ErrorBoundary>;
Here, LazyComponent is a dynamically loaded module using React.lazy and the import() function for code-splitting. The ErrorBoundary is wrapping the Suspense component. If LazyComponent fails to load, ErrorBoundary will catch it and display an error message instead of crashing the app. Suspense provides a fallback UI ('Loading...' message) while the component is being loaded.