React Server Components 28 🧬 Migration Patterns — Moving from pure client rendering to RSC
Migrating a pure client-rendered React application to RSC is not a rewrite. It is a series of boundary decisions, made one component at a time, that move data ownership and rendering responsibility from the browser to the server while keeping interactivity where it belongs. The most common mistake is the big-bang approach: marking the entire app as a Server Component and then discovering that every interactive element needs a "use client" directive, which effectively recreates the client-rendered app with extra steps. The migration that works is incremental and leaf-first. Start with the components that fetch data and render it without interaction, move them to the server, and keep the interactive islands as Client Components .
The mental model is ownership, not syntax. A component that fetches data owns the data. A component that manages state owns the interaction. In a client-rendered app, every component owns both, because the browser owns everything. In an RSC app, the server owns the data and the rendering, and the client owns the interaction. The migration is the process of untangling the two, and the tool for the untangling is the "use client" boundary, placed at the leaf rather than the root .
Key point: The migration starts with data-fetching leaf components and moves upward. Interactive components stay as Client Components with "use client". The boundary is pushed to the smallest interactive leaf, and the server content is passed through as children where a client wrapper is needed.
Why the migration is leaf-first, not root-first
The root-first failure. A developer who marks the page or layout as a Server Component and leaves the rest of the tree unchanged will find that the page cannot render, because the child components use useState and the Server Component cannot render them. The fix is to mark the children as Client Components, which pulls them and their imports into the client bundle. The result is a page that is technically an RSC page but has a client bundle identical to the original app. The migration has changed the file structure without changing the performance characteristics .
The leaf-first success. A developer who starts with a data-fetching component—a product list, a blog post, a dashboard widget—can move that component to the server without touching the interactive components around it. The data-fetching component becomes an async function that awaits the data and returns JSX. The interactive components remain Client Components, and they receive the data as props. The client bundle shrinks because the data-fetching code and its dependencies are no longer in the client graph . The interactive components are unchanged, which means the migration is reversible and incremental.
The data ownership shift. In the client-rendered app, the data-fetching component uses useEffect and fetch. The component owns the request, the loading state, the error state, and the rendering. In the RSC app, the server owns the request and the rendering, and the client receives the result as props. The useEffect disappears. The loading state is handled by Suspense. The error state is handled by an error boundary. The component becomes a pure function of its data .
The trade-off. The leaf-first migration is slower than a rewrite in the short term. It touches one component at a time, and the performance improvement is proportional to the size of the data-fetching code that moves to the server. But it is safe, reversible, and it does not block feature development. The big-bang rewrite is faster in the planning phase and slower in the execution phase, because the entire app must be converted before it can ship.
a. The four migration patterns
The patterns for restructuring a client-rendered component tree are the same patterns that apply to any RSC migration, but they are applied in a specific order during the migration.
Pattern 1: The data-fetching component. A component that uses useEffect to fetch data and renders the result is the first candidate for migration. The useEffect is removed, the component becomes async, and the fetch moves into the component body. The component is now a Server Component, and its dependencies are no longer in the client bundle .
Pattern 2: The interactive leaf. A component that uses useState, useEffect, or event handlers is the second candidate, but the migration is different. The component stays a Client Component. The "use client" directive is added to the top of the file, and the component receives its data as props from a Server Component parent. The data-fetching code is removed from the component and moved to the parent .
Pattern 3: The provider wrapper. A context provider that must wrap the entire app is a Client Component, but it can receive the rest of the app as children. The provider is marked with "use client", and the Server Component layout renders the provider with the server-rendered content as children. The provider’s state is in the client bundle, but the content is not .
Pattern 4: The composition slot. A Client Component that needs to wrap Server Component content—a modal, a carousel, a tooltip—receives the server content as children. The Client Component renders the children without importing them, and the server content remains server-rendered. This is the pattern that allows a client wrapper to exist without pulling the wrapped content into the client bundle .
// Pattern 1: The data-fetching component (before)
"use client";
import { useEffect, useState } from "react";
export function ProductList() {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch("/api/products").then(r => r.json()).then(setProducts);
}, []);
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
// Pattern 1: The data-fetching component (after)
// The component is a Server Component. The useEffect is gone.
export async function ProductList() {
const products = await db.query("SELECT * FROM products");
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
// Pattern 2: The interactive leaf (before)
"use client";
export function AddToCart({ productId }) {
const [quantity, setQuantity] = useState(1);
return <button onClick={() => addToCart(productId, quantity)}>Add</button>;
}
// Pattern 2: The interactive leaf (after)
// The component is still a Client Component.
// The data is received as props from the Server Component parent.
"use client";
export function AddToCart({ productId }) {
const [quantity, setQuantity] = useState(1);
return <button onClick={() => addToCart(productId, quantity)}>Add</button>;
}
// The Server Component parent passes the productId.
export async function ProductPage({ params }) {
const product = await db.query("SELECT * FROM products WHERE id = $1", [params.id]);
return <AddToCart productId={product.id} />;
}
The first pattern removes the data-fetching code from the client bundle. The second pattern keeps the interactive code in the client bundle but removes the data-fetching code from it. The two patterns are complementary, and they are applied in that order: first the data-fetching components, then the interactive components.
b. The incremental route migration
The route-level migration is the second layer. Once the components are restructured, the routes are moved from the client-rendered entry point to the framework’s RSC entry point. In Next.js, this is the move from the pages directory to the app directory, and it can be done one route at a time .
// The migration order for a route:
// 1. Create the app/ directory and the root layout.
// 2. Move the data-fetching logic from useEffect to an async Server Component.
// 3. Keep the interactive components as Client Components.
// 4. Pass the data from the Server Component to the Client Components as props.
// 5. Verify the route renders and the interaction works.
// 6. Delete the old route from the client-rendered entry point.
The route migration is not a file move. It is a rendering model change. The old route rendered entirely in the browser, with useEffect fetching data after the initial render. The new route renders on the server, with the data fetched before the initial render. The user sees the content immediately, and the client bundle no longer contains the data-fetching code . The interactive components are unchanged, but they receive their data as props instead of fetching it themselves.
// app/products/page.tsx — the new route
import { ProductList } from "./product-list";
import { AddToCart } from "./add-to-cart";
export default async function ProductsPage() {
// The data is fetched on the server, before the page renders.
const products = await db.query("SELECT * FROM products");
return (
<div>
{/* The ProductList is a Server Component. */}
<ProductList products={products} />
{/* The AddToCart is a Client Component. */}
<AddToCart productId={products[0].id} />
</div>
);
}
The route is now an RSC route. The ProductList renders on the server, and the AddToCart renders on the client. The data crosses the boundary as props, and the interactive component receives the data it needs without fetching it.
Complete Example Session
// ============================================
// PART 1: THE CLIENT-RENDERED APP (BEFORE)
// ============================================
// App.jsx — the entire app is a Client Component
"use client";
import { useEffect, useState } from "react";
export default function App() {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState([]);
// The data is fetched in the browser, after the initial render.
useEffect(() => {
fetch("/api/products").then(r => r.json()).then(setProducts);
}, []);
return (
<div>
<h1>Products</h1>
{products.map(p => (
<div key={p.id}>
<span>{p.name}</span>
<button onClick={() => setCart([...cart, p])}>Add to cart</button>
</div>
))}
</div>
);
}
// ============================================
// PART 2: THE DATA-FETCHING COMPONENT (PATTERN 1)
// ============================================
// app/products/product-list.tsx — a Server Component
export async function ProductList() {
// The fetch happens on the server, before the page renders.
const products = await db.query("SELECT * FROM products");
return (
<ul>
{products.map(p => (
<li key={p.id}>{p.name}</li>
))}
</ul>
);
}
// ============================================
// PART 3: THE INTERACTIVE LEAF (PATTERN 2)
// ============================================
// app/products/add-to-cart.tsx — a Client Component
"use client";
import { useState } from "react";
export function AddToCart({ productId }: { productId: string }) {
const [added, setAdded] = useState(false);
return (
<button onClick={() => { addToCart(productId); setAdded(true); }}>
{added ? "Added" : "Add to cart"}
</button>
);
}
// ============================================
// PART 4: THE PROVIDER WRAPPER (PATTERN 3)
// ============================================
// app/providers/cart-provider.tsx — a Client Component
"use client";
import { createContext, useState } from "react";
export const CartContext = createContext({});
export function CartProvider({ children }: { children: React.ReactNode }) {
const [cart, setCart] = useState([]);
return <CartContext.Provider value={{ cart, setCart }}>{children}</CartContext.Provider>;
}
// app/layout.tsx — a Server Component
import { CartProvider } from "./providers/cart-provider";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
{/* The provider is a Client Component. */}
{/* The children are Server Components passed through. */}
<CartProvider>{children}</CartProvider>
</body>
</html>
);
}
// ============================================
// PART 5: THE COMPOSITION SLOT (PATTERN 4)
// ============================================
// app/products/cart-modal.tsx — a Client Component
"use client";
import { useState } from "react";
export function CartModal({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button onClick={() => setIsOpen(true)}>Open cart</button>
{isOpen && <div className="modal">{children}</div>}
</div>
);
}
// app/products/page.tsx — a Server Component
import { CartModal } from "./cart-modal";
import { CartContents } from "./cart-contents"; // a Server Component
export default async function ProductsPage() {
return (
<CartModal>
{/* The CartContents is a Server Component. */}
{/* It is passed as children to the Client Component. */}
{/* Its code is not in the client bundle. */}
<CartContents />
</CartModal>
);
}
// ============================================
// PART 6: THE ROUTE MIGRATION
// ============================================
// The old route: pages/products.jsx (client-rendered)
// The new route: app/products/page.tsx (RSC)
// The migration steps:
// 1. Create the app/products/page.tsx file.
// 2. Move the data fetching from useEffect to the Server Component.
// 3. Keep the interactive components as Client Components.
// 4. Pass the data as props.
// 5. Verify the route works.
// 6. Delete pages/products.jsx.
// ============================================
// PART 7: THE SERVER ACTION MIGRATION
// ============================================
// The old mutation: a client-side fetch to an API route
async function addToCart(productId: string) {
await fetch("/api/cart", { method: "POST", body: JSON.stringify({ productId }) });
}
// The new mutation: a Server Action
// app/actions.ts
"use server";
export async function addToCart(productId: string) {
const session = await auth();
if (!session) throw new Error("Unauthorized");
await db.cart.create({ data: { productId, userId: session.user.id } });
revalidatePath("/products");
}
// The Client Component imports the Server Action reference.
// "use client";
// import { addToCart } from "@/app/actions";
// ============================================
// PART 8: THE MIGRATION ORDER
// ============================================
// 1. Set up the framework's RSC entry point (app/ directory).
// 2. Create the root layout (a Server Component).
// 3. Move the provider wrappers to Client Components.
// 4. Migrate the data-fetching components to Server Components.
// 5. Keep the interactive components as Client Components.
// 6. Migrate the routes one at a time.
// 7. Replace client-side API calls with Server Actions.
// 8. Remove the old client-rendered entry point.
// ============================================
// PART 9: THE VERIFICATION
// ============================================
// [ ] The data-fetching components are async Server Components.
// [ ] The interactive components have "use client".
// [ ] The data crosses the boundary as serializable props.
// [ ] The provider wrappers use children for server content.
// [ ] The composition slots use children for server content.
// [ ] The client bundle is smaller than the original.
// [ ] The interactive components still work.
// [ ] The routes render correctly.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The migration is leaf-first, not root-first.
// [ ] The data-fetching components are migrated first.
// [ ] The interactive components are migrated second.
// [ ] The providers are wrapped in Client Components.
// [ ] The composition slots use children.
// [ ] The routes are migrated one at a time.
// [ ] The Server Actions replace the client-side mutations.
// [ ] The old entry point is removed after the migration.
The ten parts covered the before state, the four patterns, the route migration, the Server Action migration, the migration order, and the verification. The through-line is that the migration is a sequence of boundary decisions, and the boundary is placed at the leaf.
Quick Reference
The migration patterns
| Pattern | Before | After |
|---|---|---|
| Data-fetching component | useEffect + fetch | async Server Component |
| Interactive leaf | Client Component with data fetching | Client Component with props |
| Provider wrapper | Client Component wrapping everything | Client Component with children |
| Composition slot | Client Component importing server content | Client Component with children |
The migration order
| Step | Action |
|---|---|
| 1 | Set up the RSC entry point |
| 2 | Create the root layout |
| 3 | Wrap providers in Client Components |
| 4 | Migrate data-fetching components |
| 5 | Keep interactive components as Client Components |
| 6 | Migrate routes one at a time |
| 7 | Replace client mutations with Server Actions |
| 8 | Remove the old entry point |
The decision rule
| Component type | Directive | Data source |
|---|---|---|
| Fetches data, no interactivity | None (Server) | Server |
| Has state, effects, or events | "use client" | Props |
| Wraps server content | "use client" with children | Children |
Best Practices
✅ Do This:
// Migrate the data-fetching component first
export async function ProductList() { const data = await db.query(); } // ✅
// Keep the interactive component as a Client Component
"use client"; export function AddToCart({ id }) { /* ... */ } // ✅
// Use children for server content in a client wrapper
<ClientWrapper>{serverContent}</ClientWrapper> // ✅
// Migrate one route at a time
// app/products/page.tsx, then app/cart/page.tsx, etc. // ✅
❌ Don’t Do This:
// Mark the page as a Client Component
"use client"; export default function Page() { /* ... */ } // ❌
// Migrate the root before the leaves
<ServerLayout><ClientApp /></ServerLayout> // the client app is huge // ❌
// Fetch data in a Client Component after the migration
"use client"; useEffect(() => { fetch(...) }, []); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The client bundle does not shrink | The "use client" directive is at the root | Move the directive to the interactive leaf |
| The page cannot render | A Server Component renders a Client Component with hooks | The Client Component is the child, not the parent |
| The provider breaks | A Client Component provider does not receive children | Pass the server content as children |
| The route does not update | The data is fetched in useEffect | Move the fetch to the Server Component |
Real-World Examples
1. Data-fetching component
export async function ProductList() { const products = await db.query(); return <ul>...</ul>; }
2. Interactive leaf
"use client"; export function AddToCart({ id }) { const [added, setAdded] = useState(false); }
3. Provider wrapper
"use client"; export function CartProvider({ children }) { return <CartContext.Provider>{children}</CartContext.Provider>; }
4. Composition slot
<CartModal><CartContents /></CartModal>
5. Route migration
// app/products/page.tsx — the new route
export default async function Page() { const data = await db.query(); }
6. Server Action migration
"use server"; export async function addToCart(id) { await db.cart.create({ data: { id } }); }
7. The old mutation
// fetch("/api/cart", { method: "POST" }) // replaced by the Server Action
8. The root layout
export default function RootLayout({ children }) { return <html><body><Providers>{children}</Providers></body></html>; }
9. The verification
// The client bundle is smaller than the original
10. The migration order
// Leaf-first, data-fetching first, interactive second
Visual
The Migration Flow
┌──────────────────────────────────────────────────────────────┐
│ FROM CLIENT-RENDERED TO RSC │
│ │
│ Before After │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ "use client" │ │ Server Component │ │
│ │ App │ │ Layout │ │
│ │ ├── ProductList │ │ ├── ProductList │ │
│ │ │ (useEffect) │ │ │ (async, server) │ │
│ │ ├── AddToCart │ │ ├── AddToCart │ │
│ │ │ (useState) │ │ │ ("use client") │ │
│ │ └── CartModal │ │ └── CartModal │ │
│ │ (useState) │ │ ("use client") │ │
│ │ │ │ │ │
│ │ Everything client │ │ Data on server │ │
│ │ Bundle: large │ │ Bundle: small │ │
│ └─────────────────────┘ └─────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
The Four Patterns
┌──────────────────────────────────────────────────────────────┐
│ THE PATTERNS, IN ORDER │
│ │
│ 1. Data-fetching component │
│ ┌─────────────────────┐ │
│ │ useEffect + fetch │──▶ async Server Component │
│ └─────────────────────┘ │
│ │
│ 2. Interactive leaf │
│ ┌─────────────────────┐ │
│ │ Client + fetch │──▶ Client + props │
│ └─────────────────────┘ │
│ │
│ 3. Provider wrapper │
│ ┌─────────────────────┐ │
│ │ Client wrapping all │──▶ Client with children │
│ └─────────────────────┘ │
│ │
│ 4. Composition slot │
│ ┌─────────────────────┐ │
│ │ Client importing │──▶ Client with children │
│ │ server content │ │
│ └─────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
The Boundary Placement
┌──────────────────────────────────────────────────────────────┐
│ ROOT BOUNDARY VS LEAF BOUNDARY │
│ │
│ ❌ Root boundary: │
│ ┌─────────────────────┐ │
│ │ "use client" │ │
│ │ Page │ │
│ │ ├── ProductList │ ← in client bundle │
│ │ ├── AddToCart │ ← in client bundle │
│ │ └── CartModal │ ← in client bundle │
│ └─────────────────────┘ │
│ │
│ ✅ Leaf boundary: │
│ ┌─────────────────────┐ │
│ │ Server Page │ │
│ │ ├── ProductList │ ← server-rendered │
│ │ ├── AddToCart │ ← "use client" │
│ │ └── CartModal │ ← "use client" │
│ └─────────────────────┘ │
│ │
│ The leaf boundary keeps the client bundle small. │
└──────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Migration strategy | Incremental, leaf-first |
| First pattern | Data-fetching component to async Server Component |
| Second pattern | Interactive leaf stays a Client Component with props |
| Third pattern | Provider wrapper with children |
| Fourth pattern | Composition slot with children |
| Route migration | One route at a time, from the client entry to the RSC entry |
| Mutation migration | Client-side fetch to Server Action |
| Verification | Smaller client bundle, working interactivity |
Key takeaways:
- The migration is leaf-first, not root-first. Marking the root as a Client Component leaves the entire tree in the client bundle. Migrating the data-fetching leaf first removes the data-fetching code from the client bundle without touching the interactive components .
- The four patterns are applied in order. The data-fetching component becomes a Server Component. The interactive leaf stays a Client Component with props. The provider wrapper becomes a Client Component with
children. The composition slot becomes a Client Component withchildren. - The route migration is one route at a time. The old route is replaced by an RSC route, and the old route is deleted after the new one is verified. The migration does not block feature development because the routes are independent .
- The Server Action replaces the client-side mutation. The
fetchcall to an API route becomes a"use server"function that the Client Component imports as a reference. The action runs on the server, and the client bundle does not contain the mutation logic . - The verification is the bundle size and the working interactivity. The client bundle should be smaller than the original. The interactive components should still work. If the bundle is not smaller, the
"use client"boundary is too high.
Remember: The migration from pure client rendering to RSC is not a rewrite. It is a sequence of boundary decisions. The data-fetching components move to the server. The interactive components stay on the client. The providers and wrappers use children to pass server content through. The routes are migrated one at a time. The mutations become Server Actions. The migration is incremental, reversible, and measurable. The measure is the client bundle size and the working interactivity. The discipline is the leaf-first order.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!