Setting Up React 19 with Server Components
Introduction
React 19 introduces Server Components that render on the server, reducing bundle size and improving performance. This guide shows how to set up and use them effectively.
Prerequisites
- Node.js >=18
- Next.js 14+ (with experimental React 19 support)
Step 1: Create Next.js Project with React 19
npx create-next-app@latest react-19-app --typescript --app-dir
cd react-19-app
npm install react@rc react-dom@rc
Step 2: Configure Next.js for React 19
Update next.config.js
:
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverComponents: true,
reactCompiler: true,
},
};
module.exports = nextConfig;
Step 3: Create Server Component
Create app/components/UserList.tsx
:
// Server Component (default in app directory)
async function fetchUsers() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
return res.json();
}
export default async function UserList() {
const users = await fetchUsers();
return (
<div>
<h2>Users (Server Component)</h2>
{users.map((user: any) => (
<div key={user.id} className="p-4 border rounded mb-2">
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
))}
</div>
);
}
Step 4: Create Client Component
Create app/components/Counter.tsx
:
'use client'
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div className="p-4 border rounded">
<h3>Counter (Client Component)</h3>
<p>Count: {count}</p>
<button
onClick={() => setCount(count + 1)}
className="bg-blue-500 text-white px-4 py-2 rounded"
>
Increment
</button>
</div>
);
}
Step 5: Compose Components
Update app/page.tsx
:
import { Suspense } from 'react';
import UserList from './components/UserList';
import Counter from './components/Counter';
export default function Home() {
return (
<main className="p-8">
<h1>React 19 Server Components Demo</h1>
<Suspense fallback={<div>Loading users...</div>}>
<UserList />
</Suspense>
<Counter />
</main>
);
}
Step 6: Optimize with Streaming
Create app/components/SlowComponent.tsx
:
async function SlowComponent() {
// Simulate slow data fetching
await new Promise(resolve => setTimeout(resolve, 3000));
return (
<div className="p-4 bg-green-100 rounded">
<h3>Slow Component Loaded!</h3>
</div>
);
}
export default SlowComponent;
Summary
React 19 Server Components enable server-side rendering with zero JavaScript bundle impact, while Client Components handle interactivity. Use Suspense
for streaming and better UX.