The user wants a React application that uses server components. This is a bit tricky because "server components" usually refers to React Server Components (RSC), which are a specific feature of React 18+ primarily used within the Next.js App Router (or other frameworks like Remix or Gatsby, or a custom setup).
Key things to consider:
Environment: RSC requires a build tool and a server environment. You can't just run a standard create-react-app client-side bundle. The standard recommendation for RSC is Next.js.
Distinction: I need to show the difference between a Server Component and a Client Component.
Structure:
Setup instructions (using Next.js).
A Server Component (fetching data).
A Client Component (interactivity).
Composition (Server rendering Client).
Code Example:
page.tsx (Server Component).
Counter.tsx (Client Component).
data-fetching.ts (simulating DB/API call).
Plan:
Clarify Prerequisites: State that RSC is best experienced with a framework like Next.js. I will provide the code based on Next.js 13/14+ (App Router).
Project Structure: Define a simple file structure.
Implementation:
Create a Server Component that fetches data (simulated async function).
Create a Client Component that handles state (button click).
Pass data from the Server Component to the Client Component to demonstrate composition.
Explanation: Explain why this improves performance (smaller bundle, faster data fetching).
How to Run: Provide commands.
Drafting the Content:
Introduction: RSC allows rendering components on the server, reducing JS sent to the client.
Step 1: Setup. npx create-next-app@latest.
Step 2: The Data (Server). I need a function that looks like a database call. getUsers().
Step 3: The Client Component. A simple interactive component. Needs 'use client' directive. Let's make a user card that allows "liking" a user. UserCard.tsx.
Step 4: The Server Page. Import UserCard. Fetch users. Map over users and render UserCard passing the data. Note that the fetch happens on the server.
Explanation: Highlight that UserCard logic (interactive) is hydrated, but the data fetching and HTML generation of the list happens on the server.
Refinement:
Is there a way to do this without Next.js? Technically yes, using the react-server-dom-webpack package directly, but that is extremely complex and usually not what a user wants unless they are building a framework. It's better to stick to the industry standard (Next.js) for a practical implementation.
Let's stick to the Next.js App Router example.
Code Snippets:
app/page.tsx: The entry point (Server Component).
app/components/UserList.tsx: Server component logic.
Self-Correction during drafting:
Make sure to emphasize the 'use client' directive. Without it, the interactive part will fail or behave unexpectedly if it uses hooks like useState. Also, emphasize async/await in the server component.
Final Output Structure:
High-level concept.
Prerequisites (Next.js).
Code blocks:
app/page.tsx (Server)
app/components/LikeButton.tsx (Client)
lib/data.ts (Mock Data)
Explanation of performance benefits.
To implement React Server Components (RSC) effectively, you need a framework that supports them. Currently, Next.js (App Router) is the industry standard for this architecture.
Below is a complete guide to building a React application using Server Components for data fetching and Client Components for interactivity.
Prerequisites
Node.js installed (v18.17 or later).
Run the following command to create a new Next.js project:
bash
npx create-next-app@latest my-rsc-app
When prompted, select Yes for "Use App Router".
The Implementation
We will build a simple dashboard that:
Fetches data on the server (Server Component). This keeps sensitive logic (API keys) secure and reduces the bundle size sent to the browser.
Renders an interactive button (Client Component).
1. The Server-Side Data Logic
Create a file to simulate a database call. This code will never run in the browser.
File:src/lib/data.ts
typescript
// This simulates a delay, like fetching from a real database
export async function getData() {
await new Promise((resolve) => setTimeout(resolve, 1000));
return {
message: "Hello from the Server!",
timestamp: new Date().toISOString(),
};
}
2. The Client Component (Interactivity)
Components that use hooks (like useState) or browser events (like onClick) must be marked as Client Components using the 'use client' directive.
File:src/components/Counter.tsx
typescript
'use client'; // This directive marks this as a Client Component
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div style={{ border: '1px solid blue', padding: '10px', margin: '10px 0' }}>
<h4>Client Component (Interactive)</h4>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
3. The Server Component (The Entry Point)
This is the default in the Next.js App Router. It fetches data and passes it down. Note that this file is async.
File:src/app/page.tsx
typescript
// We do NOT need 'use client' here. This is a Server Component.
import { getData } from '@/lib/data';
import Counter from '@/components/Counter';
// This function runs on the server only
export default async function Home() {
// Fetch data on the server
const data = await getData();
return (
<main style={{ padding: '20px', fontFamily: 'sans-serif' }}>
<h1>React Server Components Demo</h1>
{/* This section is rendered entirely on the server */}
<div style={{ border: '1px solid green', padding: '10px', marginBottom: '10px' }}>
<h3>Server Component (Static)</h3>
<p>Message: <strong>{data.message}</strong></p>
<p>Generated at: {data.timestamp}</p>
<p><small>(View Source to see this HTML was pre-rendered)</small></p>
</div>
{/* We can nest Client Components inside Server Components */}
<Counter />
</main>
);
}
Why this improves performance
Zero Bundle Size for Logic: The code inside getData (and the fact that we used async/await in page.tsx) is executed on the server. The browser never downloads that logic, nor does it download the libraries you might use to fetch data (like pg or bcrypt).
Hydration Optimization: React only needs to "hydrate" (make interactive) the Counter component. The rest of the page is pure HTML streamable immediately.
Security: If you access a database in getData, the connection string stays on the server. It is never exposed to the client-side bundle.
How to Run
Navigate into the folder: cd my-rsc-app
Run the dev server: npm run dev
Open http://localhost:3000.
Summary of Pattern
Server Components: Default. Use for fetching data, accessing backend resources, and rendering static UI.
Client Components ('use client'): Use only when you need useState, useEffect, or browser events.