Implement a React application that uses server components for improved performance.
- User
Implement a React application that uses server components for improved performance.
- Assistant
Considering React Server Components
The user is asking about implementing a React application with server components for improved performance. I think they want an explanation along with some sample code, likely using modern React with frameworks like Next.js or Vite. It's important to note that React Server Components are still evolving, and Next.js is a good starting point. I should include an example explaining server components' advantages, performance impacts, and a code sample that illustrates the project structure and key files.Creating a Minimal Demo
I want to provide a minimal example of a React application using server components, focusing on clarity without overwhelming details. The question is somewhat open, so I aim for a moderate explanation plus some relevant code, particularly using React Server Components with Next.js App Router. I think it makes sense to stick with Next.js since it's more practical for users. I plan to show code for a server component in
app/page.tsx, shared components for fetching data, and how streaming and Suspense improve performance.Structuring the React App ImplementationGiven the task to implement a React application, I’ll lay it out step by step. First, I’ll provide a brief conceptual description, followed by setup instructions using
npx create-next-app@latestwith the App Router. Instead of scripting everything, I’ll focus on key options.Next, I’ll outline essential files like
app/layout.tsx,app/page.tsx, and components such asServerProductList.tsxandClientCart.tsx. I’ll explain how to run the app without making the response too lengthy. It’s worth noting that React Server Components are supported in Next.js 13+, while the general React version remains experimental. I'll start with a paragraph on building a simple app using React Server Components.Implementing the Project StructureTo begin, I’ll show the command to create a new Next.js app:
npx create-next-app@latest my-rsc-app --ts --eslint --use-npmAfter that, I’ll provide a brief overview of the project structure.
For example, in
app/layout.tsx, I want to keep it minimal. Inapp/page.tsx, I'll include this code:import ProductList from '@/components/ProductList'; // server export default function Home() { return ( <main>... <ProductList /> </main> ); }Next, I’ll show
components/ProductList.tsxas anasynccomponent fetching data, andAddToCartButtonas a client component for interactivity. I might also include additional components for filtering or searching, while demonstrating how to set up the API route without bringing in a database.Using an External API for DemonstrationFor the demonstration, I’ll fetch product data from
https://fakestoreapi.com/productsto avoid having to set up a backend. Referencing an external API should be fine, but it does mean the app would need network access for offline runs.I want to explain that server components run exclusively on the server and aren’t shipped to the client, while client components load only when necessary, which enhances performance. I’ll also point out how we can use React Suspense for streaming.
In
page.tsx, I can add this:import { Suspense } from 'react'; import ProductList from '@/components/ProductList'; export default function Home() { return ( <> <Suspense fallback={<p>Loading products...</p>}> <ProductList /> </Suspense> </> ); }Using the App Router, fetch operations can take advantage of caching by default, which is handy.
I’ll clarify that this app employs React Server Components since components in the
appdirectory are server components by default, and only the interactive ones are marked as client components. This approach is recommended for reducing JS payload size and optimizing server data fetching.Given the user’s request for a full implementation, I’ll show the relevant code for 4-5 files along with concise instructions. I’ll avoid unnecessary disclaimers or comments about the question’s quality; let’s keep it straightforward! Below is a minimal but complete example of a React app that uses React Server Components (RSC) for better performance, implemented with Next.js (App Router)—the most practical way to use RSC today.
1. Create the project
From your terminal:
npx create-next-app@latest my-rsc-app # Answer: # ✨ TypeScript? -> Yes (recommended) # ✨ ESLint? -> Yes # ✨ App Router? -> Yes (this is required for RSC) # ✨ Tailwind? etc. -> As you like cd my-rsc-app npm run devOpen http://localhost:3000 to verify it runs.
In the App Router (
app/directory), components are Server Components by default. You opt into Client Components by adding"use client"at the top of a file.We’ll build a small products page where:
- Data fetching and rendering list = server component
- Interactive “Add to cart” button = client component
2. App layout (server component)
app/layout.tsx(server component, default):// app/layout.tsx import './globals.css'; import type { Metadata } from 'next'; export const metadata: Metadata = { title: 'RSC Demo', description: 'React Server Components with Next.js', }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body> <header style={{ padding: '1rem', borderBottom: '1px solid #ddd' }}> <h1>React Server Components Demo</h1> </header> <main style={{ padding: '1rem' }}>{children}</main> </body> </html> ); }
3. Home page using a Server Component + Suspense
app/page.tsx(server component):// app/page.tsx import { Suspense } from 'react'; import ProductList from '@/components/ProductList'; export default function HomePage() { return ( <div> <h2>Products</h2> {/* ProductList is a Server Component that fetches data on the server */} <Suspense fallback={<p>Loading products...</p>}> <ProductList /> </Suspense> </div> ); }Using
<Suspense>allows React to stream the page: the shell renders immediately, and the product list fills in as data is ready.
4. Server Component that fetches data
components/ProductList.tsx(server component, no"use client"):// components/ProductList.tsx import AddToCartButton from './AddToCartButton'; // Typing the API response (simplified) type Product = { id: number; title: string; price: number; }; async function fetchProducts(): Promise<Product[]> { // This runs on the server, not the browser const res = await fetch('https://fakestoreapi.com/products?limit=5', { // Next.js fetch has smart caching; use "no-store" if you want always-fresh // cache: 'no-store', }); if (!res.ok) { throw new Error('Failed to fetch products'); } return res.json(); } // Server Component: rendered on the server and never sent as JS to the browser export default async function ProductList() { const products = await fetchProducts(); return ( <ul style={{ listStyle: 'none', padding: 0 }}> {products.map((product) => ( <li key={product.id} style={{ marginBottom: '1rem', padding: '1rem', border: '1px solid #eee', }} > <h3>{product.title}</h3> <p>${product.price.toFixed(2)}</p> {/* AddToCartButton is a Client Component, hydrated in the browser */} <AddToCartButton productId={product.id} /> </li> ))} </ul> ); }Performance win:
ProductListand its data-fetching code never ship to the browser.- Only the serialized result (HTML + RSC payload) is sent.
- The bundle the user downloads does not include
fetchProductsor that API logic.
5. Client Component for interactivity
components/AddToCartButton.tsx(client component):// components/AddToCartButton.tsx 'use client'; import { useState, useTransition } from 'react'; type Props = { productId: number; }; export default function AddToCartButton({ productId }: Props) { const [pending, startTransition] = useTransition(); const [added, setAdded] = useState(false); const handleAdd = () => { startTransition(async () => { // Simulate a POST to an API or a server action here await new Promise((resolve) => setTimeout(resolve, 500)); setAdded(true); // In a real app you might update global state, revalidate data, etc. console.log(`Added product ${productId} to cart`); }); }; return ( <button onClick={handleAdd} disabled={pending || added} style={{ padding: '0.5rem 1rem', borderRadius: 4, border: '1px solid #333', background: added ? '#4ade80' : '#fff', cursor: pending || added ? 'not-allowed' : 'pointer', }} > {added ? 'Added!' : pending ? 'Adding…' : 'Add to cart'} </button> ); }The
"use client"directive:- Tells Next.js this component must run in the browser.
- Causes only this component (and its dependencies) to be bundled and hydrated as client-side React.
6. Run and observe
Run the app:
npm run devOpen http://localhost:3000 and:
- View View Source: you’ll see the HTML, but not the client-side React code for server components.
- Open DevTools → Network → JS: note that much less JS is loaded than a pure client-rendered app would need, because
ProductListand its data logic are not bundled for the client. - Click “Add to cart”: only the small client component is interactive.
7. Why this improves performance
- Smaller JS bundle: Most components (layout, data fetching, markup) are server-only and never shipped to the browser.
- Faster TTFB: Data is fetched directly from the server environment (close to your DB/services), not via the user’s browser.
- Streaming via Suspense: The shell appears quickly while data-heavy parts stream in.
- Less client-side work: Hydration is limited to truly interactive bits (
AddToCartButton), not your entire component tree.
If you want to extend this, you can:
- Add a
ServerSidebarcomponent (server-only) with DB queries. - Use Next.js Server Actions to perform mutations directly in server components.
- Introduce
cache/revalidateoptions onfetchfor better caching behavior.
If you tell me your preferred stack (TypeScript vs JS, Tailwind vs CSS, etc.), I can adjust this example to match it exactly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.