typescriptintermediate

Dynamic Import and Code Splitting

Use next/dynamic for lazy loading components with custom loading states, SSR control, and named exports.

typescript
import dynamic from 'next/dynamic';

// Basic dynamic import with loading fallback
const HeavyChart = dynamic(() => import('../components/HeavyChart'), {
  loading: () => (
    <div className="h-64 bg-gray-800/50 rounded-xl animate-pulse flex items-center justify-center">
      <span className="text-gray-500">Loading chart...</span>
    </div>
  ),
});

// Disable SSR for browser-only components
const MapComponent = dynamic(() => import('../components/Map'), {
  ssr: false,
  loading: () => <div className="h-96 bg-gray-800 rounded-xl animate-pulse" />,
});

// Named export import
const CodeEditor = dynamic(
  () => import('../components/Editor').then(mod => mod.CodeEditor),
  { ssr: false },
);

// Conditional dynamic import
function Dashboard({ showAnalytics }: { showAnalytics: boolean }) {
  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-white">Dashboard</h1>

      {/* Always loaded */}
      <div className="grid grid-cols-3 gap-4">
        <StatCard title="Users" value="12,345" />
        <StatCard title="Revenue" value="$45,678" />
        <StatCard title="Orders" value="890" />
      </div>

      {/* Lazy loaded on condition */}
      {showAnalytics && <HeavyChart />}

      {/* Client-only map */}
      <MapComponent />

      {/* Lazy loaded editor */}
      <CodeEditor />
    </div>
  );
}

function StatCard({ title, value }: { title: string; value: string }) {
  return (
    <div className="bg-[#111] border border-white/10 rounded-xl p-4">
      <p className="text-gray-400 text-sm">{title}</p>
      <p className="text-2xl font-bold text-white mt-1">{value}</p>
    </div>
  );
}

// Preload on hover pattern
// const HeavyModal = dynamic(() => import('./HeavyModal'));
// const preloadModal = () => import('./HeavyModal');
// <button onMouseEnter={preloadModal} onClick={() => setOpen(true)}
//   className="px-4 py-2 bg-blue-600 text-white rounded-lg">
//   Open Modal
// </button>

export default Dashboard;

Use Cases

  • Reducing initial bundle size
  • Browser-only component loading
  • Conditional feature loading

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.