| | |

React Server Components 25 🧬 Third-Party Wrappers — Making client-only libraries RSC-compatible

⏱️ Estimated read: 15 min | |

Third-party libraries were not written for the Server Component model. They were written for the client, at a time when every React component was a Client Component. The hooks they use, the browser APIs they touch, the context providers they assume—all of it was designed for an environment where window exists and useState is always available. When a Server Component imports one of these libraries, the import fails with a ReferenceError: window is not defined or a cryptic error about hooks being called outside a component. The library is not broken; it is being used in an environment it was never designed for.

The wrapper pattern is the fix. A thin Client Component wraps the library, the wrapper is marked with "use client", and the Server Component imports the wrapper instead of the library directly . The wrapper receives serializable props from the server, passes them to the library, and renders the library’s output. The library’s code is now in the client bundle, where it belongs, and the Server Component never touches it. The pattern is simple, but it has constraints: the props must be serializable, the wrapper must be as thin as possible, and the wrapper must be placed at the leaf of the component tree so that the library’s code does not pull the entire page into the client bundle .

Key point: A third-party wrapper is a Client Component that imports the client-only library and exports it (or a thin adapter around it) with "use client" at the top of the file. The Server Component imports the wrapper, not the library. The wrapper’s props must be serializable, and the wrapper should not accept or forward server-only data.


Why the wrapper is the mechanism

The library’s assumptions. A charting library like Recharts uses useState, useEffect, and window. A carousel library like acme-carousel uses hooks and event listeners. An animation library like Framer Motion uses browser APIs to measure and animate DOM nodes . These libraries cannot render on the server because the server has no DOM and no state. The wrapper does not change the library; it changes the environment. The library runs inside a Client Component, where the assumptions hold.

The "use client" boundary. The directive is placed at the top of the wrapper file, before any imports. The directive marks the file as the entry point to the client. The library’s code, and everything the library imports, becomes part of the client module graph. The Server Component that imports the wrapper does not import the library, so the library never enters the server graph . The boundary is the wrapper file, and the wrapper file is the only thing the Server Component sees.

The serializable props constraint. The wrapper receives props from the Server Component. Those props must be serializable: strings, numbers, booleans, plain objects, arrays, Date, Map, Set, and React elements (as children). A function prop is not serializable, and a class instance is not serializable . The wrapper’s props type should reflect this constraint. A wrapper that accepts a data array and a title string is a wrapper that can receive server data. A wrapper that accepts an onClick function is a wrapper that cannot.

The trade-off. Every wrapper adds a file and a component boundary. The wrapper is thin—it usually just re-exports the library or passes props through—but it is still a boundary. The library’s code is in the client bundle, and the wrapper’s props are serialized. The alternative is to use the library only in files that are already Client Components, which means the library is not used in Server Components at all. The wrapper is the mechanism that makes the library usable from a Server Component without giving up the Server Component’s data-fetching and rendering benefits.


a. The basic wrapper pattern

The simplest wrapper is a re-export. The file has the "use client" directive, imports the library, and re-exports it as the default export. The Server Component imports the wrapper, and the library is now a Client Component.

// components/chart-wrapper.tsx
"use client";

// The directive marks this file as the client boundary.
// The library is imported here, so it is included in the client bundle.
// The Server Component that imports this wrapper never imports the library.
export { Chart as default } from "some-chart-library";
// app/dashboard/page.tsx — a Server Component
import Chart from "@/components/chart-wrapper";

export default async function DashboardPage() {
  const data = await db.query("SELECT * FROM metrics");

  // The Chart is a Client Component.
  // The data is serialized and sent to the client.
  // The chart library's code is in the client bundle.
  return <Chart data={data} title="Metrics" />;
}

The wrapper is three lines. It does not transform the props, does not add logic, and does not change the library’s API. The only thing it does is establish the client boundary . The Server Component imports the wrapper, and the wrapper imports the library. The import chain stops at the wrapper for the server, and continues through the wrapper for the client.

The wrapper’s props type must be serializable. If the library’s component accepts a data array, the wrapper accepts a data array. If the library’s component accepts a formatter function, the wrapper cannot accept a function from a Server Component. The function would have to be a Server Function ("use server") or the formatting would have to happen on the server before the data is passed .


b. The adapter wrapper and the composition pattern

A wrapper does not have to be a pure re-export. It can be a thin adapter that transforms the props or composes the library with server-rendered children. The adapter is still a Client Component, but it adds a layer between the library and the Server Component.

// components/carousel-wrapper.tsx
"use client";

import { Carousel } from "acme-carousel";

export function CarouselWrapper({ items, children }: { items: string[]; children: React.ReactNode }) {
  // The wrapper receives the items as a serializable array.
  // The children are server-rendered content passed through.
  // The Carousel is a client-only library.
  return (
    <Carousel items={items}>
      {children}
    </Carousel>
  );
}
// app/page.tsx — a Server Component
import { CarouselWrapper } from "@/components/carousel-wrapper";
import { ProductCard } from "./product-card"; // a Server Component

export default async function Page() {
  const products = await db.query("SELECT * FROM products");
  const items = products.map((p) => p.name);

  return (
    // The CarouselWrapper is a Client Component.
    // The ProductCard components are Server Components passed as children.
    // The ProductCard code is not in the client bundle.
    <CarouselWrapper items={items}>
      {products.map((p) => <ProductCard key={p.id} product={p} />)}
    </CarouselWrapper>
  );
}

The composition pattern is the way to keep server content out of the client bundle while still using the client library as the wrapper. The children prop is a React element that the Server Component renders. The wrapper receives it as a prop and renders it inside the library’s component. The wrapper’s module never imports the ProductCard module, so the ProductCard code is not in the client bundle . The wrapper is the client boundary, and the children are the server content that crosses the boundary as JSX, not as an import.

The adapter wrapper is the pattern for libraries that need a specific prop shape. The library might expect an items array and a renderItem function. The wrapper receives the serializable items array and the server-rendered children, and it passes the items to the library. The renderItem function is defined inside the wrapper, so it is a client function, not a serialized prop .


Complete Example Session

// ============================================
// PART 1: THE PROBLEM — DIRECT IMPORT IN A SERVER COMPONENT
// ============================================

// app/page.tsx — a Server Component
import { Chart } from "recharts"; // ❌ the library uses window

export default function Page() {
  return <Chart data={data} />;
}

// Build error or runtime error:
// ReferenceError: window is not defined
// Recharts uses useState and window internally.
// It cannot run on the server.

// ============================================
// PART 2: THE WRAPPER — RE-EXPORT
// ============================================

// components/chart-wrapper.tsx
"use client";

// The re-export is the simplest wrapper.
// The library is imported here, in a Client Component.
// The Server Component imports this file, not the library.
export { LineChart as Chart } from "recharts";

// ============================================
// PART 3: THE SERVER COMPONENT — USING THE WRAPPER
// ============================================

// app/page.tsx — a Server Component
import { Chart } from "@/components/chart-wrapper";

export default async function Page() {
  const data = await db.query("SELECT * FROM metrics");

  // The Chart is now a Client Component.
  // The data is serialized and passed as a prop.
  return <Chart data={data} />;
}

// The recharts code is in the client bundle.
// The Server Component never imports recharts.

// ============================================
// PART 4: THE ADAPTER WRAPPER
// ============================================

// components/carousel-wrapper.tsx
"use client";

import { Carousel } from "acme-carousel";

export function CarouselWrapper({
  items,
  children,
}: {
  items: string[];
  children: React.ReactNode;
}) {
  // The items are a serializable array.
  // The children are server-rendered content.
  return <Carousel items={items}>{children}</Carousel>;
}

// ============================================
// PART 5: THE COMPOSITION PATTERN
// ============================================

// app/page.tsx — a Server Component
import { CarouselWrapper } from "@/components/carousel-wrapper";
import { ProductCard } from "./product-card"; // a Server Component

export default async function Page() {
  const products = await db.query("SELECT * FROM products");
  const items = products.map((p) => p.name);

  return (
    <CarouselWrapper items={items}>
      {products.map((p) => (
        <ProductCard key={p.id} product={p} />
      ))}
    </CarouselWrapper>
  );
}

// The ProductCard is a Server Component.
// Its code is not in the client bundle.
// The CarouselWrapper is the client boundary.
// The children cross the boundary as JSX, not as an import.

// ============================================
// PART 6: THE NON-SERIALIZABLE PROP
// ============================================

// ❌ The wrapper cannot accept a function from a Server Component.
// The function is not serializable.
export function BadWrapper({ onClick }: { onClick: () => void }) {
  return <Library onClick={onClick} />;
}

// ✅ The function must be a Server Function, or the logic must move.
"use server";
export async function handleClick() {
  // server logic
}

// The Server Component passes the Server Function reference.
// The wrapper receives a serializable reference, not a function.

// ============================================
// PART 7: THE LEAF PLACEMENT
// ============================================

// The wrapper should be at the leaf, not at the root.
// A wrapper at the root pulls the entire page into the client bundle.
// A wrapper at the leaf pulls only the library.

// ❌ The wrapper wraps the entire page.
export default function Page() {
  return (
    <ChartWrapper>
      <Header />
      <Sidebar />
      <MainContent />
    </ChartWrapper>
  );
}

// ✅ The wrapper wraps only the chart.
export default function Page() {
  return (
    <div>
      <Header />
      <Sidebar />
      <MainContent />
      <ChartWrapper data={data} />
    </div>
  );
}

// ============================================
// PART 8: THE PROVIDER WRAPPER
// ============================================

// Some libraries export a provider that must be rendered at the root.
// The provider is a Client Component, but the root layout is a Server Component.
// The wrapper is the fix.

// components/providers.tsx
"use client";

import { ThemeProvider } from "next-themes";
import { SessionProvider } from "next-auth/react";

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <SessionProvider>
      <ThemeProvider>{children}</ThemeProvider>
    </SessionProvider>
  );
}

// app/layout.tsx — a Server Component
import { Providers } from "@/components/providers";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

// The Providers are Client Components.
// The children are Server Components passed through.
// The provider's code is in the client bundle.
// The children's code is not.

// ============================================
// PART 9: THE LIBRARY THAT SHIPS "use client"
// ============================================

// Some libraries already ship "use client" in their build output.
// These libraries can be imported directly into Server Components.
// The wrapper is not needed.

// If the library has the directive:
// import { Button } from "some-lib"; // ✅ works in a Server Component
//
// If the library does not have the directive:
// import { Button } from "some-lib"; // ❌ fails
// Use the wrapper instead.

// The React documentation recommends that library authors
// add "use client" to their components .

// ============================================
// PART 10: THE VERIFICATION CHECKLIST
// ============================================

// [ ] The wrapper file has "use client" at the top.
// [ ] The wrapper imports the client-only library.
// [ ] The Server Component imports the wrapper, not the library.
// [ ] The wrapper's props are serializable.
// [ ] The wrapper is placed at the leaf, not the root.
// [ ] The wrapper uses the composition pattern for server content.
// [ ] The build succeeds without "window is not defined".

The ten parts covered the direct import problem, the re-export wrapper, the Server Component usage, the adapter wrapper, the composition pattern, the non-serializable prop, the leaf placement, the provider wrapper, the library that ships the directive, and the verification. The through-line is that the wrapper is a client boundary, and the Server Component never touches the library.


Quick Reference

The wrapper pattern

PatternWrapper contentUse case
Re-exportexport { X } from "lib"Simple component, no prop transformation
AdapterFunction that transforms propsLibrary needs a specific prop shape
ProviderWrapper around a context providerLibrary requires a root provider
CompositionWrapper with childrenServer content inside a client library

The constraints

ConstraintRule
"use client"Must be at the top of the wrapper file
PropsMust be serializable
PlacementAt the leaf, not the root
Server contentPassed as children, not imported

Common client-only libraries

LibraryCategoryWrapper needed
RechartsChartsYes
Chart.jsChartsYes
Framer MotionAnimationYes
React SpringAnimationYes
MUIUI componentsYes (interactive)
React Hook FormFormsYes

Best Practices

✅ Do This:

// Put "use client" at the top of the wrapper
"use client"; export { Chart } from "recharts";                 // ✅

// Pass serializable props
<Chart data={data} title="Metrics" />                           // ✅

// Use composition for server content
<CarouselWrapper items={items}>{serverChildren}</CarouselWrapper> // ✅

// Place the wrapper at the leaf
<ChartWrapper data={data} />                                    // ✅

❌ Don’t Do This:

// Import the library directly in a Server Component
import { Chart } from "recharts";                               // ❌

// Pass a function from a Server Component
<Chart formatter={(x) => x} /> // not serializable              // ❌

// Put the wrapper at the root
<Wrapper><Header /><Main /></Wrapper> // entire page in client   // ❌

Common Pitfalls

PitfallWhy It HappensFix
window is not definedLibrary imported in a Server ComponentWrap it in a "use client" file
Props are not serializableFunction passed from Server ComponentUse a Server Function or move the logic
Entire page in client bundleWrapper at the rootMove the wrapper to the leaf
Provider errorThird-party provider without "use client"Wrap the provider in a Client Component
Library already has "use client"Unnecessary wrapperImport the library directly

Real-World Examples

1. Recharts wrapper

"use client"; export { LineChart as Chart } from "recharts";

2. Framer Motion wrapper

"use client"; import { motion } from "framer-motion"; export const MotionDiv = motion.div;

3. Carousel adapter

"use client"; export function CarouselWrapper({ items, children }) { return <Carousel items={items}>{children}</Carousel>; }

4. Provider wrapper

"use client"; export function Providers({ children }) { return <SessionProvider>{children}</SessionProvider>; }

5. Composition pattern

<CarouselWrapper items={items}>{serverProducts}</CarouselWrapper>

6. Leaf placement

<ChartWrapper data={data} /> // not wrapping the page

7. Non-serializable prop

// ❌ <Chart onClick={() => {}} />
// ✅ <Chart action={serverAction} />

8. Provider in layout

<Providers>{children}</Providers>

9. Library with directive

import { Button } from "some-lib"; // works if the lib has "use client"

10. Build verification

next build # no "window is not defined" error

Visual

The Wrapper Boundary

┌──────────────────────────────────────────────────────────────┐
│  SERVER COMPONENT AND CLIENT WRAPPER                          │
│                                                              │
│  Server Component                                            │
│  ┌──────────────────────────────────────────────┐           │
│  │ import { Chart } from "./chart-wrapper"      │           │
│  │                                              │           │
│  │ <Chart data={data} />                        │           │
│  │                                              │           │
│  │ The Server Component does not import recharts│           │
│  └──────────────────────┬───────────────────────┘           │
│                         │                                    │
│                         ▼                                    │
│  Client Wrapper                                              │
│  ┌──────────────────────────────────────────────┐           │
│  │ "use client"                                 │           │
│  │ export { LineChart as Chart } from "recharts"│           │
│  │                                              │           │
│  │ The wrapper imports recharts.                │           │
│  │ The library is in the client bundle.         │           │
│  └──────────────────────────────────────────────┘           │
└──────────────────────────────────────────────────────────────┘

The Composition Pattern

┌──────────────────────────────────────────────────────────────┐
│  SERVER CONTENT AS CHILDREN                                   │
│                                                              │
│  Server Component                                            │
│  ┌──────────────────────────────────────────────┐           │
│  │ <CarouselWrapper items={items}>              │           │
│  │   <ProductCard product={p} />  ← Server      │           │
│  │ </CarouselWrapper>                            │           │
│  └──────────────────────┬───────────────────────┘           │
│                         │                                    │
│                         ▼                                    │
│  Client Wrapper                                              │
│  ┌──────────────────────────────────────────────┐           │
│  │ "use client"                                 │           │
│  │ export function CarouselWrapper({ items,      │           │
│  │   children }) {                              │           │
│  │   return <Carousel items={items}>            │           │
│  │     {children}                               │           │
│  │   </Carousel>;                               │           │
│  │ }                                            │           │
│  │                                              │           │
│  │ The ProductCard code is not in the client    │           │
│  │ bundle. The children cross as JSX.           │           │
│  └──────────────────────────────────────────────┘           │
└──────────────────────────────────────────────────────────────┘

The Leaf Placement

┌──────────────────────────────────────────────────────────────┐
│  ROOT WRAPPER VS LEAF WRAPPER                                 │
│                                                              │
│  ❌ Root wrapper:                                             │
│  ┌─────────────────────┐                                    │
│  │ <Wrapper>           │                                    │
│  │   <Header />        │  ← Header is in the client bundle  │
│  │   <Main />          │  ← Main is in the client bundle    │
│  │   <Chart />         │  ← Chart is in the client bundle   │
│  │ </Wrapper>          │                                    │
│  └─────────────────────┘                                    │
│                                                              │
│  ✅ Leaf wrapper:                                             │
│  ┌─────────────────────┐                                    │
│  │ <Header />          │  ← Server Component                │
│  │ <Main />            │  ← Server Component                │
│  │ <ChartWrapper />    │  ← Client Component                │
│  └─────────────────────┘                                    │
│                                                              │
│  The leaf wrapper keeps the client bundle small.            │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Pattern"use client" wrapper file
Wrapper contentRe-export, adapter, or provider
PropsMust be serializable
Server contentPassed as children
PlacementAt the leaf, not the root
Library with "use client"No wrapper needed
Common librariesRecharts, Chart.js, Framer Motion, MUI

Key takeaways:

  • The wrapper is a Client Component that imports the library. The "use client" directive at the top of the wrapper file establishes the boundary. The Server Component imports the wrapper, and the library’s code enters the client bundle, not the server bundle .
  • The wrapper’s props must be serializable. A data array and a title string are serializable. A function is not. The Server Component cannot pass an event handler to the wrapper unless the handler is a Server Function ("use server") .
  • The composition pattern keeps server content out of the client bundle. The wrapper can receive server-rendered content as children. The wrapper renders the children without importing them, so the children’s code remains on the server .
  • The wrapper should be at the leaf, not the root. A wrapper at the root pulls the entire page into the client bundle. A wrapper at the leaf pulls only the library. The placement is the difference between a small client bundle and a large one .
  • Some libraries already ship the directive. A library that includes "use client" in its build output can be imported directly into a Server Component. The wrapper is only necessary for libraries that do not have the directive .

Remember: A third-party wrapper is a client boundary, not a transformation. It exists to move the library’s code into the client bundle and to keep the Server Component’s code out of it. The wrapper should be as thin as possible, its props should be serializable, and it should be placed at the leaf of the component tree. The library was written for the client; the wrapper gives it the client environment it expects. The Server Component fetches the data and passes it across the boundary, and the library renders it on the client. The wrapper is the bridge.

Was this helpful?


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!