Course contentsShow
← React
Lesson 1408 of 2,39635. Code SplittingFree lesson

Tab Panel Lazy Loading

Load tab content only when the tab is activated, avoiding loading all panels upfront.

Tab Panel Lazy Loading

You'll learn how to load tab content only when users click on a tab, keeping your initial page load fast and efficient.

Imagine a hotel where each room (tab panel) has its own air conditioning unit. You don't turn on the AC in all rooms at once—you only activate it when a guest actually enters that room. Tab panel lazy loading works the same way: instead of loading all tab content upfront (even the tabs users never click), you load each panel's content only when its tab becomes active.

Why Lazy Load Tabs?

When you have tabs with heavy content—data tables, charts, forms, or complex components—loading everything at once wastes bandwidth and slows down your initial render. Most users only view one or two tabs anyway. By combining React's interaction-based lazy loading pattern with tab state, you defer loading until necessary.

The Core Pattern

Track which tab is active using state. Use conditional rendering to mount the lazy component only when its tab is selected. Here's the mental model:

// Each tab panel gets lazy loaded
const HeavyPanel = React.lazy(() => import('./HeavyPanel'));

function TabContainer() {
  const [activeTab, setActiveTab] = React.useState('summary');

  return (
    <div>
      <button onClick={() => setActiveTab('summary')}>Summary</button>
      <button onClick={() => setActiveTab('details')}>Details</button>

      <Suspense fallback={<div>Loading panel...</div>}>
        {activeTab === 'summary' && <SummaryPanel />}
        {activeTab === 'details' && <HeavyPanel />}
      </Suspense>
    </div>
  );
}

When the user clicks "Details" for the first time, React triggers the dynamic import for HeavyPanel, shows the fallback spinner, then renders the content. Subsequent clicks use the already-loaded component.

Key Takeaway: Combine tab state with conditional rendering and React.lazy() to load each tab's content only when activated, dramatically reducing initial load time for tab-heavy interfaces.