Course contentsShow
← Web Development
Lesson 1947 of 2,98236. Performance Optimization TechniquesFree lesson

Error Boundaries for Failed Chunk Loading

Handling network failures and chunk loading errors gracefully with error boundaries and retry logic.

Error Boundaries for Failed Chunk Loading

What you'll learn: How to catch and recover from chunk loading failures in code-split applications using error boundaries and retry logic.

When you dynamically import code chunks (as we've been doing with code splitting), network failures or deployment mismatches can cause those chunks to fail loading. Without proper error handling, users see blank screens or cryptic browser errors. Error boundaries are React's mechanism for catching JavaScript errors anywhere in the component tree and displaying fallback UI instead of crashing the entire app.

Understanding the Problem

Think of code splitting like ordering food delivery. Sometimes the delivery fails—the restaurant is closed, the driver gets lost, or the app crashes. You need a backup plan, not just starvation!

When a dynamically imported chunk fails to load (network timeout, 404 on old chunk after deployment, etc.), JavaScript throws an error. Without catching it, your app breaks.

Implementing Error Boundaries for Chunks

Error boundaries are class components that implement componentDidCatch() or static getDerivedStateFromError(). They catch errors in child components during rendering, lifecycle methods, and—crucially—in dynamic imports.

class ChunkErrorBoundary extends React.Component {
  state = { hasError: false, chunkError: false };

  static getDerivedStateFromError(error) {
    // Check if it's a chunk loading error
    const isChunkError = /Loading chunk [\d]+ failed/.test(error.message);
    return { hasError: true, chunkError: isChunkError };
  }

  handleRetry = () => {
    this.setState({ hasError: false });
    window.location.reload(); // Force fresh chunk fetch
  };

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h2>Something went wrong loading this page.</h2>
          {this.state.chunkError && (
            <button onClick={this.handleRetry}>Retry</button>
          )}
        </div>
      );
    }
    return this.props.children;
  }
}

Wrap your lazily-loaded routes or components with this boundary to catch chunk failures and offer users a retry option.

Key Takeaway: Error boundaries prevent chunk loading failures from crashing your app, letting you display user-friendly fallbacks and implement retry logic for network issues.