DEV Community

Cover image for πŸš€ React Server Components in Next.js 15
Neel Shah
Neel Shah

Posted on Edited on

πŸš€ React Server Components in Next.js 15

React and Next.js have introduced powerful new capabilities to enhance performance and scalability in modern web applications. One of the most notable features is React Server Components (RSC), which enable rendering parts of your UI on the serverβ€”reducing client-side JavaScript and improving load times.

In this guide, we’ll explore how RSC works in Next.js 15 by building a practical GitHub User Explorer app. You’ll learn how to separate server and client logic, fetch data efficiently, and apply clean UI patternsβ€”all in a way that’s beginner-friendly and perfect for strengthening your portfolio.

🧠 Note: This post is written for beginners trying out React Server Components for the first time, especially in the context of Next.js 15.


πŸ“‹ Table of Contents


Introduction to React Server Components βš›οΈ

React Server Components (RSC) allow you to fetch, process, and render UI on the server, delivering only HTML to the client. The client gets a minimal JavaScript bundle, keeps sensitive logic secure, and improves performance. In Next.js 15, RSC is built into the App Router, making server-client composability seamless.

Key Advantages

  • πŸš€ Performance: Smaller bundles, faster loads
  • πŸ”’ Security: API keys/logic stay server-side
  • 🧹 Clean Code Separation: Server for data, client for interactivity

Visualizing Server vs Client Components

Understanding the difference between Server Components and Client Components is crucial when working with Next.js 15 and React Server Components (RSC). Here’s a simple visual to help clarify:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        Server Component     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ βœ… Runs on the server       β”‚
β”‚ βœ… Can access backend APIs  β”‚
β”‚ βœ… Can query the database   β”‚
β”‚ βœ… No JS sent to browser    β”‚
β”‚ ❌ Cannot use hook(useState)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             ↓
      Passes HTML only
             ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        Client Component     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ βœ… Runs in the browser      β”‚
β”‚ βœ… Can use useState, events β”‚
β”‚ βœ… Supports interactivity   β”‚
β”‚ ❌ Cannot access backend    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Enter fullscreen mode Exit fullscreen mode

Project Architecture & Tech Stack πŸ› οΈ

Our GitHub User Explorer lets you:

  • πŸ”Ž Enter a GitHub username
  • πŸ“Š Fetch the user's profile and public repositories from GitHub’s official API
  • πŸ› οΈ Interactively filter repositories by language

Stack Breakdown:

Technology Purpose
Next.js 15 First-class RSC support, React framework
React Modern component-based UI
Tailwind CSS Utility-first, mobile-friendly styling
GitHub API Real-time profiles and repository data
ESLint, Prettier Format and code-quality automation
Husky, Lint-Staged Pre-commit code safety

Server-Side Data Fetching πŸ—„οΈ

The main server component (page.tsx) fetches both user info and the list of public repos, handling responses and errors for a smooth experience.

// This is a React Server Component in Next.js 15
// It fetches GitHub user details and their repositories on the server side

import { GitHubUser, Repo } from '../types';
import RepoListClient from './Components/RepoListClient';

// Base URL for GitHub API
const GITUSERURL = `https://api.github.com/users`;

export default async function UserPage({
  params,
}: {
  params: Promise<{ username: string }>;
}) {
  // Await the route params β€” username is dynamic
  const { username } = await params;

  // Fetch user and repos in parallel for better performance
  const [userRes, repoRes] = await Promise.all([
    fetch(`${GITUSERURL}/${username}`), // Fetch user details
    fetch(`${GITUSERURL}/${username}/repos`, {
      // Fetch user repositories with revalidation every 60s
      next: { revalidate: 60 },
    }),
  ]);

  // If the user is not found, show a fallback UI
  if (!userRes.ok) {
    return <div className="p-4">User not found</div>;
  }

  // Parse the responses as JSON
  const user: GitHubUser = await userRes.json();
  const repos: Repo[] = repoRes.ok ? await repoRes.json() : [];

  return (
    <div className="space-y-6 p-6">
      {/* User profile section */}
      <div className="flex items-center gap-4">
        <img
          src={user.avatar_url}
          alt={user.login}
          className="w-20 rounded-full"
        />
        <div>
          <h2 className="text-xl">{user.name}</h2>
          <p className="text-gray-600">@{user.login}</p>
          <p>{user.bio}</p>
        </div>
      </div>

      {/* Client component to render repo list */}
      <RepoListClient repos={repos} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • πŸ”„ Concurrent Fetching: Profile & repos load in parallel
  • ⚑ Optimized Data: Revalidates every 60 seconds
  • 🚫 User Feedback: β€œUser not found” for invalid usernames

Client Components for Interactive UI πŸŽ›οΈ

RSC handle server data, but your app also needs interactivityβ€”the job of client components.

RepoListClient.tsx

RepoListClient.tsx is a Client Component that conditionally renders a filterable list of repositories. It uses the RepoFilter component internally and gracefully handles the case when no public repositories exist.

'use client'; // This is a Client Component since it uses interactivity via RepoFilter

import { Repo } from '../../types';
import RepoFilter from './RepoFilter';

// This component displays the user's public GitHub repositories with filtering
export default function RepoListClient({ repos }: { repos: Repo[] }) {
  // Handle case when user has no public repositories
  if (!repos || repos.length === 0) {
    return (
      <div className="text-gray-700 dark:text-gray-300">
        This user has no public repositories.
      </div>
    );
  }

  return (
    <div className="mt-6">
      {/* Section heading */}
      <h2 className="mb-2 text-xl font-semibold text-black dark:text-white">
        Public Repositories
      </h2>

      {/* Render the RepoFilter component to allow filtering by language */}
      <RepoFilter repos={repos} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

RepoFilter.tsx

Lets users filter repositories by language with instant updates.

'use client'; // Mark this as a Client Component

import { useState } from 'react';
import { Repo } from '../../types';

// A filterable list of GitHub repositories based on programming language
export default function RepoFilter({ repos }: { repos: Repo[] }) {
  // State to track selected language for filtering
  const [selectedLang, setSelectedLang] = useState('All');

  // Get unique list of languages from repo data
  const languages = Array.from(
    new Set(repos.map((repo) => repo.language).filter(Boolean)) // Filter out null/undefined
  );

  // Apply filtering logic
  const filteredRepos =
    selectedLang === 'All'
      ? repos // Show all repos if "All" is selected
      : repos.filter((repo) => repo.language === selectedLang); // Filter by selected language

  return (
    <div>
      {/* Language filter buttons */}
      <div className="mb-4 flex flex-wrap gap-2">
        <button
          onClick={() => setSelectedLang('All')}
          className={`rounded px-3 py-1 ${
            selectedLang === 'All'
              ? 'bg-blue-600 text-white' // Highlight selected
              : 'bg-gray-200 dark:bg-gray-700 dark:text-white'
          }`}
        >
          All
        </button>

        {/* Render a button for each unique language */}
        {languages.map((lang) => (
          <button
            key={lang}
            onClick={() => setSelectedLang(lang)}
            className={`rounded px-3 py-1 ${
              selectedLang === lang
                ? 'bg-blue-600 text-white'
                : 'bg-gray-200 dark:bg-gray-700 dark:text-white'
            }`}
          >
            {lang}
          </button>
        ))}
      </div>

      {/* Filtered repo list */}
      <ul className="space-y-4">
        {filteredRepos.map((repo) => (
          <li
            key={repo.id}
            className="rounded border border-gray-300 bg-white p-4 text-black dark:border-gray-700 dark:bg-gray-800 dark:text-white"
          >
            {/* Repo name linking to GitHub */}
            <a
              href={repo.html_url}
              target="_blank"
              rel="noopener noreferrer"
              className="font-semibold text-blue-600 dark:text-blue-400"
            >
              {repo.name}
            </a>

            {/* Description */}
            <p className="text-sm text-gray-600 dark:text-gray-300">
              {repo.description || 'No description'}
            </p>

            {/* Programming language tag */}
            <span className="rounded bg-gray-200 px-2 py-1 text-sm dark:bg-gray-700">
              {repo.language || 'Unknown'}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • 🧠 Dynamic Filter: Only shows languages found in user repos
  • ⚑ Instant UI: Filtering updates instantly, no extra fetches!

Connecting Server and Client Logic πŸ”—

  • πŸ”„ Data fetched server-side is passed as props to the client component tree.
  • πŸŽ›οΈ Client components handle interactivity without further server or API calls.
  • πŸ” Sensitive API logic always stays on the server.

Styling with Tailwind CSS 🎨

Tailwind CSS provides a responsive, visually appealing, and maintainable UI:

  • 🎨 Modern design with utility classes (borders, spacing, colors)
  • πŸ“± Responsive for both desktop and mobile
  • πŸŒ— Instant dark mode support

Do’s and Don’ts of Server Components

To use React Server Components effectively in Next.js 15, follow these best practices:

Do’s
βœ… Use async/await to fetch data directly in the component
βœ… Access backend services like databases, APIs, or secret environment variables
βœ… Keep the components stateless and pure
βœ… Import and compose other Server Components
βœ… Use next: { revalidate: 60 } for caching and revalidation

Don’ts
❌ Don’t use hooks like useState, useEffect, or useContext
❌ Don’t access browser APIs like window, localStorage, or navigator
❌ Don’t import client-only libraries (e.g., react-toastify, chart.js)
❌ Don’t write event handlers like onClick inside server components

Best Practices & Patterns βœ…

  • 🏎️ Parallel Data Fetching: Use Promise.all to speed up dependent API loads
  • πŸ›‘οΈ User-Facing Errors: Never show broken UIsβ€”always give user-friendly error states
  • 🧹 Separation of Concerns: Server for data, client for UI, clear file organization
  • 🚦 Automated Checks: Quality tools keep your codebase reliable & readable

Demo 🎬

See the app in action! Here’s a walkthrough of searching users and filtering their repositories:

Demo

Running the Demo Locally πŸƒβ€β™‚οΈ

git clone https://github.com/Neel2651/github-explorer-rsc.git
cd github-explorer-rsc
npm install
npm run dev

Visit http://localhost:3000, and search any GitHub username to dynamically explore their public repositories!

Enhancements & Practice Tips 🌟

  • βž• Add pagination, infinite scroll, or more advanced search
  • 🎨 Show followers/following, repo stats, and avatars
  • ⚑ Optimize further with Next.js server actions, advanced caching, or SWR for stale-while-revalidate data management
  • πŸš€ Deploy on Vercel or Netlify

Published App & Resources πŸ“’

Conclusion πŸŽ‰

React Server Components in Next.js 15 offer a powerful framework for building robust, blazing-fast, and highly interactive web applications. By combining server-powered data fetching with rich, client-side UI interactions, you’ll stand out as a developer ready for the modern web.

Try the app, extend it for your practice. Happy coding! πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

If you enjoyed this guide, please like and share! Follow for more developer tutorials and real-world project walkthroughs.

Top comments (0)