Skip to content
Rabat, Morocco
Tutorials

Building High-Performance Next.js Apps with React Server Components, Streaming, and Suspense

November 30, 2025
Building High-Performance Next.js Apps with React Server Components, Streaming, and Suspense
So you want to build blazing-fast Next.js applications? That's awesome! React Server Components, Streaming, and Suspense are honestly game-changers. They're not just buzzwords - they're the foundation of modern, high-performance web applications. Here's what makes this so exciting: you can now build apps that load instantly, stream content progressively, and ship way less JavaScript to the client. It's like having superpowers for web performance. In this tutorial, we're going to build a production-ready Next.js application that leverages:
  • React Server Components - Render components on the server, reduce bundle size
  • Streaming SSR - Send HTML in chunks as it's ready
  • Suspense Boundaries - Show loading states while data fetches
  • Selective Hydration - Only hydrate what's needed, when it's needed
  • Progressive Enhancement - Works even if JavaScript fails
By the end, you'll understand how to build applications that feel instant, even when loading complex data. Let me tell you why this is so important right now. Traditional React apps have a problem: they send everything to the client, wait for JavaScript to load, then render. This creates:
  • Large JavaScript bundles - Everything ships to the client
  • Slow Time to Interactive (TTI) - Users wait for hydration
  • Poor Core Web Vitals - Bad LCP, FID, and CLS scores
  • Wasted resources - Rendering things that don't need interactivity
Server Components solve this by:
  • Rendering on the server - HTML is ready immediately
  • Reducing bundle size - Only ship what needs interactivity
  • Streaming content - Show things as they're ready
  • Better SEO - Content is in the HTML from the start
Pretty powerful, right? Let's build something amazing. Before we dive in, make sure you have:
  • Node.js 18+ installed
  • Next.js 14+ (we'll use the App Router)
  • Basic understanding of React and async/await
  • A code editor with TypeScript support
Got everything? Great! Let's get started. First, let's create a new Next.js project:
npx create-next-app@latest performance-app --typescript --tailwind --app
cd performance-app
We'll be using the App Router, which is required for Server Components. Make sure your
next.config.js
is set up correctly:
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    // Server Components are stable in Next.js 14+
  },
};

module.exports = nextConfig;
Before we start building, let me explain what Server Components actually are. They're different from traditional React components: Server Components (default in App Router):
  • Run only on the server
  • Can directly access databases and APIs
  • Don't ship to the client bundle
  • Can't use browser APIs or hooks like
    useState
  • Perfect for data fetching and static content
Client Components (marked with
'use client'
):
  • Run on both server and client
  • Can use hooks and browser APIs
  • Ship to the client bundle
  • Perfect for interactivity
Here's the key insight: use Server Components by default, and only mark components as Client Components when you need interactivity. Let's start simple. Create a Server Component that fetches data:
// app/products/page.tsx
import { Suspense } from 'react';

// This is a Server Component - no 'use client' directive
async function getProducts() {
  // Simulate API call
  await new Promise(resolve => setTimeout(resolve, 1000));

  return [
    { id: 1, name: 'Product 1', price: 29.99 },
    { id: 2, name: 'Product 2', price: 39.99 },
    { id: 3, name: 'Product 3', price: 49.99 },
  ];
}

// Server Component - runs on server only
async function ProductsList() {
  const products = await getProducts();

  return (
    <div className="grid grid-cols-3 gap-4">
      {products.map(product => (
        <div key={product.id} className="p-4 border rounded">
          <h3 className="font-bold">{product.name}</h3>
          <p className="text-gray-600">${product.price}</p>
        </div>
      ))}
    </div>
  );
}

// Loading component
function ProductsLoading() {
  return (
    <div className="grid grid-cols-3 gap-4">
      {[1, 2, 3].map(i => (
        <div key={i} className="p-4 border rounded animate-pulse">
          <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
          <div className="h-4 bg-gray-200 rounded w-1/2"></div>
        </div>
      ))}
    </div>
  );
}

// Page component
export default function ProductsPage() {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">Products</h1>
      <Suspense fallback={<ProductsLoading />}>
        <ProductsList />
      </Suspense>
    </div>
  );
}
This is a Server Component! Notice:
  • No
    'use client'
    directive
  • Direct async/await for data fetching
  • No hooks or browser APIs
  • Renders on the server
Now let's make this even better with streaming. The magic happens when you wrap async components in Suspense:
// app/dashboard/page.tsx
import { Suspense } from 'react';

// Simulate different loading times
async function getFastData() {
  await new Promise(resolve => setTimeout(resolve, 500));
  return { message: 'Fast data loaded!' };
}

async function getSlowData() {
  await new Promise(resolve => setTimeout(resolve, 2000));
  return { message: 'Slow data loaded!' };
}

async function getMediumData() {
  await new Promise(resolve => setTimeout(resolve, 1000));
  return { message: 'Medium data loaded!' };
}

// Fast component
async function FastSection() {
  const data = await getFastData();
  return <div className="p-4 bg-green-100 rounded">{data.message}</div>;
}

// Medium component
async function MediumSection() {
  const data = await getMediumData();
  return <div className="p-4 bg-yellow-100 rounded">{data.message}</div>;
}

// Slow component
async function SlowSection() {
  const data = await getSlowData();
  return <div className="p-4 bg-blue-100 rounded">{data.message}</div>;
}

export default function DashboardPage() {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">Dashboard</h1>

      <div className="space-y-4">
        {/* These stream independently! */}
        <Suspense fallback={<div className="p-4 bg-gray-100 rounded animate-pulse">Loading fast...</div>}>
          <FastSection />
        </Suspense>

        <Suspense fallback={<div className="p-4 bg-gray-100 rounded animate-pulse">Loading medium...</div>}>
          <MediumSection />
        </Suspense>

        <Suspense fallback={<div className="p-4 bg-gray-100 rounded animate-pulse">Loading slow...</div>}>
          <SlowSection />
        </Suspense>
      </div>
    </div>
  );
}
What's happening here? Each Suspense boundary streams independently! The fast section appears first, then medium, then slow. Users see content progressively, not all at once. Let's build something more realistic - a blog with multiple data sources:
// app/blog/page.tsx
import { Suspense } from 'react';

// Simulate database queries
async function getFeaturedPosts() {
  await new Promise(resolve => setTimeout(resolve, 800));
  return [
    { id: 1, title: 'Featured Post 1', excerpt: 'This is a featured post...' },
    { id: 2, title: 'Featured Post 2', excerpt: 'Another featured post...' },
  ];
}

async function getRecentPosts() {
  await new Promise(resolve => setTimeout(resolve, 1200));
  return [
    { id: 3, title: 'Recent Post 1', excerpt: 'Recent content...' },
    { id: 4, title: 'Recent Post 2', excerpt: 'More recent content...' },
  ];
}

async function getCategories() {
  await new Promise(resolve => setTimeout(resolve, 600));
  return [
    { id: 1, name: 'Technology', count: 12 },
    { id: 2, name: 'Design', count: 8 },
    { id: 3, name: 'Business', count: 5 },
  ];
}

// Server Components
async function FeaturedPosts() {
  const posts = await getFeaturedPosts();

  return (
    <section className="mb-8">
      <h2 className="text-2xl font-bold mb-4">Featured Posts</h2>
      <div className="grid grid-cols-2 gap-4">
        {posts.map(post => (
          <article key={post.id} className="p-4 border rounded">
            <h3 className="font-bold text-lg mb-2">{post.title}</h3>
            <p className="text-gray-600">{post.excerpt}</p>
          </article>
        ))}
      </div>
    </section>
  );
}

async function RecentPosts() {
  const posts = await getRecentPosts();

  return (
    <section className="mb-8">
      <h2 className="text-2xl font-bold mb-4">Recent Posts</h2>
      <div className="space-y-4">
        {posts.map(post => (
          <article key={post.id} className="p-4 border rounded">
            <h3 className="font-bold text-lg mb-2">{post.title}</h3>
            <p className="text-gray-600">{post.excerpt}</p>
          </article>
        ))}
      </div>
    </section>
  );
}

async function Categories() {
  const categories = await getCategories();

  return (
    <aside className="p-4 bg-gray-50 rounded">
      <h2 className="text-xl font-bold mb-4">Categories</h2>
      <ul className="space-y-2">
        {categories.map(category => (
          <li key={category.id} className="flex justify-between">
            <span>{category.name}</span>
            <span className="text-gray-500">({category.count})</span>
          </li>
        ))}
      </ul>
    </aside>
  );
}

// Loading components
function FeaturedPostsLoading() {
  return (
    <section className="mb-8">
      <h2 className="text-2xl font-bold mb-4">Featured Posts</h2>
      <div className="grid grid-cols-2 gap-4">
        {[1, 2].map(i => (
          <div key={i} className="p-4 border rounded animate-pulse">
            <div className="h-6 bg-gray-200 rounded w-3/4 mb-2"></div>
            <div className="h-4 bg-gray-200 rounded w-full"></div>
          </div>
        ))}
      </div>
    </section>
  );
}

function RecentPostsLoading() {
  return (
    <section className="mb-8">
      <h2 className="text-2xl font-bold mb-4">Recent Posts</h2>
      <div className="space-y-4">
        {[1, 2].map(i => (
          <div key={i} className="p-4 border rounded animate-pulse">
            <div className="h-6 bg-gray-200 rounded w-3/4 mb-2"></div>
            <div className="h-4 bg-gray-200 rounded w-full"></div>
          </div>
        ))}
      </div>
    </section>
  );
}

function CategoriesLoading() {
  return (
    <aside className="p-4 bg-gray-50 rounded animate-pulse">
      <div className="h-6 bg-gray-200 rounded w-1/2 mb-4"></div>
      <div className="space-y-2">
        {[1, 2, 3].map(i => (
          <div key={i} className="h-4 bg-gray-200 rounded"></div>
        ))}
      </div>
    </aside>
  );
}

// Main page
export default function BlogPage() {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-4xl font-bold mb-8">Blog</h1>

      <div className="grid grid-cols-3 gap-8">
        <div className="col-span-2">
          {/* These stream independently */}
          <Suspense fallback={<FeaturedPostsLoading />}>
            <FeaturedPosts />
          </Suspense>

          <Suspense fallback={<RecentPostsLoading />}>
            <RecentPosts />
          </Suspense>
        </div>

        <aside>
          <Suspense fallback={<CategoriesLoading />}>
            <Categories />
          </Suspense>
        </aside>
      </div>
    </div>
  );
}
Notice how each section loads independently? Categories appear first (600ms), then Featured Posts (800ms), then Recent Posts (1200ms). Users see content progressively! Now let's add interactivity. We'll create a Client Component that works with Server Components:
// components/AddToCartButton.tsx
'use client'; // This makes it a Client Component

import { useState } from 'react';

interface AddToCartButtonProps {
  productId: number;
  productName: string;
}

export function AddToCartButton({ productId, productName }: AddToCartButtonProps) {
  const [isAdding, setIsAdding] = useState(false);
  const [added, setAdded] = useState(false);

  const handleAddToCart = async () => {
    setIsAdding(true);

    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 500));

    setIsAdding(false);
    setAdded(true);

    setTimeout(() => setAdded(false), 2000);
  };

  return (
    <button
      onClick={handleAddToCart}
      disabled={isAdding || added}
      className={`px-4 py-2 rounded ${
        added
          ? 'bg-green-500 text-white'
          : isAdding
          ? 'bg-gray-400 cursor-not-allowed'
          : 'bg-blue-500 text-white hover:bg-blue-600'
      }`}
    >
      {added ? 'Added!' : isAdding ? 'Adding...' : 'Add to Cart'}
    </button>
  );
}
Now use it in a Server Component:
// app/products/[id]/page.tsx
import { AddToCartButton } from '@/components/AddToCartButton';

async function getProduct(id: string) {
  await new Promise(resolve => setTimeout(resolve, 500));
  return {
    id: parseInt(id),
    name: `Product ${id}`,
    price: 29.99,
    description: 'This is a great product!',
  };
}

export default async function ProductPage({ params }: { params: { id: string } }) {
  const product = await getProduct(params.id);

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-4">{product.name}</h1>
      <p className="text-2xl text-gray-600 mb-4">${product.price}</p>
      <p className="mb-6">{product.description}</p>

      {/* Client Component used in Server Component */}
      <AddToCartButton productId={product.id} productName={product.name} />
    </div>
  );
}
This is the pattern: Server Components fetch data, Client Components handle interactivity. The Server Component renders the product data, and the Client Component handles the button click. Let's explore some advanced patterns. Here's how to handle errors with error boundaries:
// app/products/error.tsx
'use client'; // Error boundaries must be Client Components

'use client';

export default function ProductsError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div className="container mx-auto p-8">
      <h2 className="text-2xl font-bold mb-4">Something went wrong!</h2>
      <p className="text-gray-600 mb-4">{error.message}</p>
      <button
        onClick={reset}
        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
      >
        Try again
      </button>
    </div>
  );
}
Use it with error boundaries:
// app/products/page.tsx
import { Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

async function getProducts() {
  // Simulate potential error
  if (Math.random() > 0.8) {
    throw new Error('Failed to fetch products');
  }

  await new Promise(resolve => setTimeout(resolve, 1000));
  return [
    { id: 1, name: 'Product 1', price: 29.99 },
    { id: 2, name: 'Product 2', price: 39.99 },
  ];
}

async function ProductsList() {
  const products = await getProducts();

  return (
    <div className="grid grid-cols-3 gap-4">
      {products.map(product => (
        <div key={product.id} className="p-4 border rounded">
          <h3 className="font-bold">{product.name}</h3>
          <p className="text-gray-600">${product.price}</p>
        </div>
      ))}
    </div>
  );
}

function ErrorFallback({ error, resetErrorBoundary }: any) {
  return (
    <div className="p-4 bg-red-100 rounded">
      <p className="text-red-800 mb-2">Error: {error.message}</p>
      <button
        onClick={resetErrorBoundary}
        className="px-4 py-2 bg-red-500 text-white rounded"
      >
        Retry
      </button>
    </div>
  );
}

export default function ProductsPage() {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">Products</h1>
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        <Suspense fallback={<div>Loading products...</div>}>
          <ProductsList />
        </Suspense>
      </ErrorBoundary>
    </div>
  );
}
Here's a pro tip: fetch multiple data sources in parallel:
// app/dashboard/page.tsx
import { Suspense } from 'react';

async function getUser() {
  await new Promise(resolve => setTimeout(resolve, 800));
  return { id: 1, name: 'John Doe', email: 'john@example.com' };
}

async function getNotifications() {
  await new Promise(resolve => setTimeout(resolve, 600));
  return [
    { id: 1, message: 'New message received' },
    { id: 2, message: 'Task completed' },
  ];
}

async function getStats() {
  await new Promise(resolve => setTimeout(resolve, 1000));
  return {
    views: 1234,
    likes: 567,
    shares: 89,
  };
}

// Fetch in parallel using Promise.all
async function DashboardContent() {
  // These fetch in parallel, not sequentially!
  const [user, notifications, stats] = await Promise.all([
    getUser(),
    getNotifications(),
    getStats(),
  ]);

  return (
    <div className="space-y-6">
      <section>
        <h2 className="text-2xl font-bold mb-4">Welcome, {user.name}!</h2>
        <p className="text-gray-600">{user.email}</p>
      </section>

      <section>
        <h2 className="text-2xl font-bold mb-4">Notifications</h2>
        <ul className="space-y-2">
          {notifications.map(notif => (
            <li key={notif.id} className="p-2 bg-gray-100 rounded">
              {notif.message}
            </li>
          ))}
        </ul>
      </section>

      <section>
        <h2 className="text-2xl font-bold mb-4">Stats</h2>
        <div className="grid grid-cols-3 gap-4">
          <div className="p-4 bg-blue-100 rounded">
            <p className="text-2xl font-bold">{stats.views}</p>
            <p className="text-gray-600">Views</p>
          </div>
          <div className="p-4 bg-green-100 rounded">
            <p className="text-2xl font-bold">{stats.likes}</p>
            <p className="text-gray-600">Likes</p>
          </div>
          <div className="p-4 bg-purple-100 rounded">
            <p className="text-2xl font-bold">{stats.shares}</p>
            <p className="text-gray-600">Shares</p>
          </div>
        </div>
      </section>
    </div>
  );
}

export default function DashboardPage() {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-4xl font-bold mb-8">Dashboard</h1>
      <Suspense fallback={<div>Loading dashboard...</div>}>
        <DashboardContent />
      </Suspense>
    </div>
  );
}
Using
Promise.all
means all three requests happen simultaneously, not one after another. Much faster!
Let's create better loading states. Here's a pattern I love:
// components/SkeletonLoader.tsx
export function SkeletonLoader({ className = '' }: { className?: string }) {
  return (
    <div className={`animate-pulse ${className}`}>
      <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
      <div className="h-4 bg-gray-200 rounded w-1/2"></div>
    </div>
  );
}

// components/ProductCardSkeleton.tsx
export function ProductCardSkeleton() {
  return (
    <div className="p-4 border rounded">
      <div className="h-48 bg-gray-200 rounded mb-4 animate-pulse"></div>
      <div className="h-6 bg-gray-200 rounded w-3/4 mb-2 animate-pulse"></div>
      <div className="h-4 bg-gray-200 rounded w-1/2 mb-4 animate-pulse"></div>
      <div className="h-10 bg-gray-200 rounded w-full animate-pulse"></div>
    </div>
  );
}

// Use in Suspense fallback
<Suspense fallback={<ProductCardSkeleton />}>
  <ProductCard />
</Suspense>
Here are some performance tips I've learned:
import dynamic from 'next/dynamic';

// Only load this component when needed
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
  loading: () => <div>Loading chart...</div>,
  ssr: false, // Don't render on server if not needed
});

export default function AnalyticsPage() {
  return (
    <div>
      <h1>Analytics</h1>
      <HeavyChart />
    </div>
  );
}
import { unstable_cache } from "next/cache";

const getCachedProducts = unstable_cache(
  async () => {
    // Your data fetching logic
    return await fetchProducts();
  },
  ["products"], // Cache key
  {
    revalidate: 3600, // Revalidate every hour
  }
);
// app/products/page.tsx
export const revalidate = 3600; // Revalidate every hour
export const dynamic = "force-static"; // Pre-render at build time

export default function ProductsPage() {
  // ...
}
Let's add performance monitoring:
// lib/performance.ts
export function measurePerformance(name: string) {
  if (typeof window !== "undefined" && "performance" in window) {
    const start = performance.now();

    return () => {
      const end = performance.now();
      console.log(`${name} took ${end - start}ms`);
    };
  }

  return () => {};
}

// Use it
const endMeasure = measurePerformance("ProductsList");
const products = await getProducts();
endMeasure();
Here's what I've learned building high-performance Next.js apps: Only mark components as Client Components when you need:
  • Interactivity (onClick, onChange, etc.)
  • Browser APIs (localStorage, window, etc.)
  • React hooks (useState, useEffect, etc.)
Don't wrap everything in one Suspense boundary. Create multiple boundaries so content streams independently:
// ❌ Bad - everything waits for everything
<Suspense fallback={<LoadingAll />}>
  <Header />
  <Content />
  <Sidebar />
</Suspense>

// ✅ Good - each streams independently
<Suspense fallback={<HeaderLoading />}>
  <Header />
</Suspense>
<Suspense fallback={<ContentLoading />}>
  <Content />
</Suspense>
<Suspense fallback={<SidebarLoading />}>
  <Sidebar />
</Suspense>
Use
Promise.all
to fetch multiple data sources simultaneously:
// ❌ Bad - sequential fetching
const user = await getUser();
const posts = await getPosts();
const comments = await getComments();

// ✅ Good - parallel fetching
const [user, posts, comments] = await Promise.all([
  getUser(),
  getPosts(),
  getComments(),
]);
Make loading states match the final content structure. This prevents layout shift:
// ✅ Good - skeleton matches content
<Suspense fallback={<ProductCardSkeleton />}>
  <ProductCard />
</Suspense>
If you have a slow API, wrap it in Suspense so other content can render:
// Fast content renders immediately
<FastContent />

// Slow content streams when ready
<Suspense fallback={<SlowContentLoading />}>
  <SlowContent />
</Suspense>
Problem: Adding
'use client'
to components that don't need it.
Solution: Only add
'use client'
when you need interactivity or browser APIs.
Problem: All content waits for the slowest data source. Solution: Wrap each async component in its own Suspense boundary. Problem: Waiting for each API call to finish before starting the next. Solution: Use
Promise.all
to fetch in parallel.
Problem: Generic loading spinner causes layout shift. Solution: Create skeleton loaders that match your content structure. When deploying:
  1. Enable Streaming: Make sure your hosting provider supports streaming (Vercel, Netlify do)
  2. Monitor Performance: Use tools like Vercel Analytics or Lighthouse CI
  3. Test Core Web Vitals: Ensure LCP, FID, and CLS scores are good
  4. Optimize Images: Use Next.js Image component for automatic optimization
  5. Bundle Analysis: Use
    @next/bundle-analyzer
    to check bundle sizes
Congratulations! You've learned how to build high-performance Next.js applications with React Server Components, Streaming, and Suspense. Here's what we covered:
  • ✅ Understanding Server vs Client Components
  • ✅ Implementing streaming with Suspense
  • ✅ Building real-world examples
  • ✅ Combining Server and Client Components
  • ✅ Advanced patterns and optimizations
  • ✅ Performance best practices
The combination of Server Components, Streaming, and Suspense creates applications that:
  • Load instantly
  • Stream content progressively
  • Ship minimal JavaScript
  • Provide excellent user experiences
Start with these patterns and iterate. Your users will thank you!
  1. Experiment: Try different Suspense boundary placements
  2. Measure: Use performance tools to see the impact
  3. Optimize: Identify slow data sources and wrap them in Suspense
  4. Monitor: Track Core Web Vitals in production
  5. Iterate: Keep improving based on real user data
Happy building! 🚀

Enjoyed this tutorial?

Seriously, thank you for spending your time here. If you made it to the end, you’re the kind of person who cares about craft, not just quick fixes.If you’d like to support my work, pick one (no pressure). It genuinely helps me keep writing and improving these tutorials.
Subscribe to get a heads-up when I publish the next one. I keep it low-volume, and I only send what I’d personally want to read.

Subscribe to Josias's Newsletter

I occasionally write about software engineering, technology, and share thoughts on innovation and engineering.
One last thing: if you know someone who’d benefit from this, sharing it with them is one of the best compliments you can give. I appreciate you.