### Streaming with React Suspense - Basic Example
Source: https://context7.com/kiki-le-singe/nextjs-perf-showcase/llms.txt
Implements server-side streaming using React Suspense to progressively load content. It includes an asynchronous component simulating API delay and a skeleton component for fallback UI. This pattern allows static content to display immediately while dynamic content streams in.
```tsx
// src/app/streaming/basic/page.tsx
import { Suspense } from "react";
// Async component that simulates API delay
async function UserProfile() {
await new Promise((resolve) => setTimeout(resolve, 2000));
return (
JD
John Doe
Software Engineer
Last seen 2 hours ago
);
}
// Skeleton component displays while async content loads
function UserProfileSkeleton() {
return (
);
}
export default function Page() {
return (
{/* Static content shows immediately */}
Navigation & Header
This content loads instantly while other parts stream in.
{/* Streamed content with fallback skeleton */}
}>
);
}
```
--------------------------------
### Dynamic Import WaveSurfer.js for Audio Player - TypeScript React
Source: https://context7.com/kiki-le-singe/nextjs-perf-showcase/llms.txt
This component dynamically imports the WaveSurfer.js library on user interaction (hover or play click) to create an audio player with visualization. It handles loading, playback, error states, and cleans up the WaveSurfer instance on component unmount. Dependencies include React hooks and the wavesurfer.js library.
```tsx
"use client";
import { useState, useRef, useEffect } from "react";
import type WaveSurfer from "wavesurfer.js";
type WaveSurferModule = typeof import("wavesurfer.js");
export default function AudioPlayer({ audioUrl }: { audioUrl: string }) {
const waveformRef = useRef(null);
const wavesurferRef = useRef(null);
const wavesurferLibRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
// Preload WaveSurfer on hover
async function preloadWaveSurfer() {
if (!wavesurferLibRef.current) {
wavesurferLibRef.current = await import("wavesurfer.js");
}
}
async function handlePlayPause() {
// Toggle play/pause if already loaded
if (wavesurferRef.current) {
wavesurferRef.current.playPause();
return;
}
// First time: load library and initialize
setIsLoading(true);
setError(null);
try {
await preloadWaveSurfer();
const WaveSurfer = wavesurferLibRef.current!.default;
wavesurferRef.current = WaveSurfer.create({
container: waveformRef.current!,
waveColor: "#4F4A85",
progressColor: "#383351",
url: audioUrl,
height: 80,
barWidth: 2,
barRadius: 3,
});
wavesurferRef.current.on("ready", () => {
setIsLoading(false);
wavesurferRef.current!.play();
});
wavesurferRef.current.on("play", () => setIsPlaying(true));
wavesurferRef.current.on("pause", () => setIsPlaying(false));
wavesurferRef.current.on("finish", () => setIsPlaying(false));
wavesurferRef.current.on("error", (err: Error) => {
setError(err.message);
setIsLoading(false);
});
} catch {
setError("Failed to load audio player");
setIsLoading(false);
}
}
useEffect(() => {
return () => {
if (wavesurferRef.current) {
wavesurferRef.current.destroy();
wavesurferRef.current = null;
}
};
}, []);
return (
);
}
```
--------------------------------
### Dynamically Load Modal Component with Next.js
Source: https://context7.com/kiki-le-singe/nextjs-perf-showcase/llms.txt
This code snippet shows how to dynamically import a Modal component using Next.js's `dynamic` function. The component is only loaded when the `isModalOpen` state becomes true, ensuring it's not part of the initial page load. This is useful for components that are not immediately required.
```tsx
"use client";
import dynamic from "next/dynamic";
import { useState } from "react";
// Modal component loaded only when opened
const Modal = dynamic(() => import("./modal-component"));
export default function DynamicModalDemo() {
const [isModalOpen, setIsModalOpen] = useState(false);
return (
<>
Simple Modal Example
Click the button below to dynamically load and open a modal.
The modal component is not included in the initial page bundle.
How It Works
• Modal component is dynamically imported with dynamic()
• Code is downloaded only when button is clicked
• Subsequent opens are instant (code is cached)
• Initial bundle stays lightweight
{/* Modal component is conditionally rendered and dynamically loaded */}
{isModalOpen && (
setIsModalOpen(false)} />
)}
>
);
}
```
--------------------------------
### Dashboard Streaming with Suspense - Next.js
Source: https://context7.com/kiki-le-singe/nextjs-perf-showcase/llms.txt
This code snippet demonstrates dashboard streaming using Next.js's Suspense component. It allows for progressive rendering of multiple components, each with its own simulated loading time. A fallback UI (MetricCardSkeleton) is displayed while the actual component data is being fetched.
```tsx
// src/app/streaming/dashboard/page.tsx
import { Suspense } from "react";
// Each card has different loading times (500ms, 1000ms, 1500ms, 2000ms)
async function RevenueCard() {
await new Promise((resolve) => setTimeout(resolve, 500));
return (
Total Revenue
$45,231
+20.1% from last month
);
}
function MetricCardSkeleton() {
return (
);
}
export default function Page() {
return (
{/* Header loads immediately */}
Analytics Overview
Your business metrics for this month
{/* Multiple cards stream in progressively */}
}>
}>
}>
}>
);
}
```
--------------------------------
### Dynamic Import of Chart.js in React Component
Source: https://context7.com/kiki-le-singe/nextjs-perf-showcase/llms.txt
This React component uses dynamic imports to load the Chart.js library asynchronously. It registers necessary modules and creates a chart instance only after the library is loaded and the component is mounted. The chart is destroyed on unmount to prevent memory leaks. It handles loading states and preloads the library on hover for a better user experience.
```tsx
"use client";
import { useState, useRef, useEffect } from "react";
type ChartModule = typeof import("chart.js");
type ChartInstance = import("chart.js").Chart;
export default function ChartSection() {
const [showChart, setShowChart] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const chartRef = useRef(null);
const chartInstanceRef = useRef(null);
const chartLibRef = useRef(null);
useEffect(() => {
if (showChart && chartRef.current && !chartInstanceRef.current && chartLibRef.current) {
createChart();
}
}, [showChart]);
// Dynamic import of Chart.js (~200KB)
async function loadChartLibrary() {
if (chartLibRef.current) return chartLibRef.current;
const chartModule = await import("chart.js");
chartModule.Chart.register(...chartModule.registerables);
chartLibRef.current = chartModule;
return chartModule;
}
async function loadChart() {
if (chartInstanceRef.current) return;
setShowChart(true);
setIsLoading(true);
try {
await loadChartLibrary();
} catch (error) {
console.error("Failed to load chart:", error);
} finally {
setIsLoading(false);
}
}
function createChart() {
if (!chartRef.current || !chartLibRef.current) return;
chartInstanceRef.current = new chartLibRef.current.Chart(chartRef.current, {
type: "bar",
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May"],
datasets: [{
label: "Sales (€)",
data: [1200, 1900, 800, 1500, 2200],
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 2,
}],
},
options: {
responsive: true,
scales: { y: { beginAtZero: true } },
},
});
}
// Preload on hover for instant feel
async function preloadChart() {
try {
await loadChartLibrary();
} catch (error) {
console.error("Failed to preload chart:", error);
}
}
useEffect(() => {
return () => {
if (chartInstanceRef.current) {
chartInstanceRef.current.destroy();
}
};
}, []);
return (
Sales Dashboard
{showChart && (
)}
);
}
```
--------------------------------
### Dynamic Tab Component Loading in Next.js
Source: https://context7.com/kiki-le-singe/nextjs-perf-showcase/llms.txt
This component dynamically imports different tab contents using `next/dynamic`. Each tab is a separate chunk loaded only when activated, improving performance for dashboards. It uses React's `useState` to manage the active tab and renders the corresponding component.
```tsx
"use client";
import dynamic from "next/dynamic";
import { useState } from "react";
// Each tab component is dynamically imported
const TabOverview = dynamic(() => import("./tab-overview"));
const TabCharts = dynamic(() => import("./tab-charts"));
const TabReports = dynamic(() => import("./tab-reports"));
const TabUsers = dynamic(() => import("./tab-users"));
const tabs = {
tabOverview: TabOverview,
tabCharts: TabCharts,
tabReports: TabReports,
tabUsers: TabUsers,
};
export default function DynamicTabsDemo() {
const [activeTab, setActiveTab] = useState("tabOverview");
const ActiveTabContent = tabs[activeTab as keyof typeof tabs];
return (
Dashboard Tabs
{/* Tab Navigation */}
{/* Tab Content - dynamically loaded */}
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.