AboutProjectsWorkBlogContact
Home / Blog / Next.js, React & TypeScript

Solving Server and Client Component Problems in Next.js

The errors you will actually hit with Server and Client Components, why they happen and how to fix them.

By Hamza JanzaibNovember 28, 202612 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • next.js
  • server-components
  • react
  • debugging
On this page · 12 sections
  • The model in one minute
  • Problem 1: "You're importing a component that needs useState"
  • Problem 2: Props that cannot be serialized
  • Problem 3: Context providers and the "provider must be a client component" wall
  • Problem 4: Third-party components that break on the server
  • Problem 5: Hydration mismatches
  • Problem 6: Server-only code leaking into the client
  • Problem 7: Using request APIs in the wrong place
  • A quick decision guide
  • Debugging tips
  • Best practices
  • Conclusion

The Server and Client Component model is one of the most powerful parts of the App Router, and the source of a predictable set of errors. They all come from one idea: code runs in two places, and a file is on one side of a boundary or the other. This guide lists the errors you will actually meet, explains why each happens and shows how to fix it without turning your whole app into client code.

The model in one minute

  • Server Components (the default) run on the server, can read data directly, and ship no JavaScript for themselves.
  • Client Components (files with "use client") are also prerendered on the server, then hydrated in the browser so they can hold state, run effects and handle events.
  • A "use client" directive marks a boundary. That module and everything it imports belong to the client bundle.
  • Data crossing from server to client must be serializable: strings, numbers, booleans, arrays, plain objects, dates, and a few other supported types, plus Server Actions.

Keep that picture in your head and most errors explain themselves.

Problem 1: "You're importing a component that needs useState"

Symptom. A build or dev error says a component uses a client-only hook, such as useState, useEffect or useRef, but is being used in a Server Component.

Why. Server Components cannot hold state or run effects. A hook in a file without "use client" runs on the server where it does not make sense.

Fix. Push the interactive part down into its own Client Component and keep the page on the server:

tsx
// app/products/like-button.tsx"use client";import { useState } from "react";export function LikeButton({ initialCount }: { initialCount: number }) {  const [count, setCount] = useState(initialCount);  return <button onClick={() => setCount((c) => c + 1)}>♥ {count}</button>;}
tsx
// app/products/page.tsx (Server Component)import { LikeButton } from "./like-button";import { getProducts } from "@/lib/products";export default async function Page() {  const products = await getProducts();  return products.map((p) => (    <article key={p.id}>      <h2>{p.name}</h2>      <LikeButton initialCount={p.likes} />    </article>  ));}

The data fetching stays on the server, and only the small button ships JavaScript.

Common mistake: adding "use client" to the whole page to silence the error. It works, but it moves data fetching and a large amount of JavaScript to the client.

Problem 2: Props that cannot be serialized

Symptom. An error like "Functions cannot be passed directly to Client Components" or a complaint about a class instance or Map.

Why. Props crossing the boundary are serialized into the response. Plain functions, class instances with methods and non-serializable objects cannot be.

Fix options:

  1. Pass plain data and let the client component decide what to do.
  2. Pass a Server Action for server-side behavior. Actions serialize as references.
  3. Move the function into the Client Component if it only runs there.
tsx
// Server Componentimport { saveNote } from "./actions";import { NoteForm } from "./note-form";export default function Page() {  // saveNote is a Server Action ("use server"), so it can cross the boundary  return <NoteForm onSave={saveNote} />;}
ts
// app/notes/actions.ts"use server";export async function saveNote(formData: FormData) {  const text = String(formData.get("text") ?? "").trim();  if (!text) throw new Error("Text is required");  await db.notes.insert({ text });}

If you need to pass something like a Map, convert it to an array of entries (or a plain object) first.

Problem 3: Context providers and the "provider must be a client component" wall

Symptom. createContext is not a function or a similar error when using React context.

Why. Context is a client feature. A provider has to be a Client Component.

Fix. Put the provider in its own client file, accept children, and render it as low in the tree as practical:

tsx
// app/providers/theme-provider.tsx"use client";import { createContext, useContext, useState, type ReactNode } from "react";const ThemeContext = createContext<"light" | "dark">("light");export const useTheme = () => useContext(ThemeContext);export function ThemeProvider({ children }: { children: ReactNode }) {  const [theme] = useState<"light" | "dark">("light");  return <ThemeContext value={theme}>{children}</ThemeContext>;}
tsx
// app/layout.tsx (Server Component)import { ThemeProvider } from "./providers/theme-provider";export default function RootLayout({ children }: { children: React.ReactNode }) {  return (    <html lang="en">      <body>        <ThemeProvider>{children}</ThemeProvider>      </body>    </html>  );}

The children you pass are still Server Components. Wrapping them in a client provider does not turn them into client code.

Problem 4: Third-party components that break on the server

Symptom. An imported library component throws on the server because it uses state, effects or browser APIs, but the package does not declare "use client".

Fix. Make your own thin wrapper that adds the directive, and import the wrapper everywhere:

tsx
// components/carousel.tsx"use client";import { Carousel } from "some-carousel-library";export default Carousel;

For components that cannot render on the server at all (they touch window at import time), load them only on the client:

tsx
"use client";import dynamic from "next/dynamic";const Map = dynamic(() => import("./map"), {  ssr: false,  loading: () => <p>Loading map…</p>,});

Note that ssr: false is only allowed in Client Components.

Problem 5: Hydration mismatches

Symptom. "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties", or text content that differs.

Why. On first render the client must produce exactly the HTML the server produced. Anything that differs between the two breaks hydration. The usual causes:

CauseExampleFix
Non-deterministic valuesDate.now(), Math.random() during renderGenerate in an effect, or pass a value from the server
Locale-dependent formattingtoLocaleString() without a fixed locale and timezoneSpecify locale and timeZone, or format on one side only
Browser-only checkstypeof window !== "undefined" in renderUse useSyncExternalStore or an effect
Invalid HTML nesting<div> inside <p>, <a> inside <a>Fix the markup
Browser extensionsAttributes injected into <body>suppressHydrationWarning on that element

A safe pattern for values that only exist in the browser is useSyncExternalStore, which accepts a separate server snapshot:

tsx
"use client";import { useSyncExternalStore } from "react";const subscribe = (cb: () => void) => {  window.addEventListener("online", cb);  window.addEventListener("offline", cb);  return () => {    window.removeEventListener("online", cb);    window.removeEventListener("offline", cb);  };};export function OnlineStatus() {  const online = useSyncExternalStore(    subscribe,    () => navigator.onLine, // client snapshot    () => true,             // server snapshot (must match first client render)  );  return <span>{online ? "Online" : "Offline"}</span>;}

For dates, render an unambiguous string on the server and format on the client only after mount, or use a fixed timezone:

tsx
new Date(iso).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });

Use suppressHydrationWarning sparingly. It silences the warning for a single element's attributes or text and does not fix mismatches deeper in the tree. It is appropriate for known external causes, like a browser extension adding attributes to <body>.

Problem 6: Server-only code leaking into the client

Symptom. A database client or secret shows up in a client bundle, or the build fails because a client file imported Node-only modules.

Fix. Mark modules that must never run in the browser:

ts
// lib/db.tsimport "server-only";import { PrismaClient } from "@prisma/client";export const db = new PrismaClient();

Now any Client Component that imports this module, directly or indirectly, produces a build error. Do the same for modules that read secrets. Environment variables without the NEXT_PUBLIC_ prefix are not exposed to the browser, but server-only protects against accidentally moving the logic.

Problem 7: Using request APIs in the wrong place

cookies(), headers() and params exist only on the server and are asynchronous. Calling them in a Client Component fails. Read them in a Server Component and pass the value down as a prop. With Cache Components enabled, the component that reads them must also be wrapped in a <Suspense> boundary so the rest of the page can be prerendered.

tsx
import { cookies } from "next/headers";import { Suspense } from "react";import { ThemeToggle } from "./theme-toggle"; // Client Componentasync function ThemeSwitcher() {  const theme = (await cookies()).get("theme")?.value ?? "light";  return <ThemeToggle initialTheme={theme} />;}export default function Header() {  return (    <Suspense fallback={null}>      <ThemeSwitcher />    </Suspense>  );}

A quick decision guide

  • Needs state, effects, event handlers or browser APIs → Client Component.
  • Reads data, uses secrets or heavy libraries → Server Component.
  • Needs both → server parent, small client child, passing serializable props.
  • Wraps third-party code that needs the client → client wrapper file.
  • Provides context → client provider that accepts children.

Debugging tips

  • Read the stack trace for the import chain: it shows which file crossed the boundary.
  • Search for "use client" and ask whether each one is as low in the tree as it can be.
  • Use the browser network tab to see how much JavaScript a route ships, and your bundle analyzer to find heavy client dependencies.
  • Reproduce hydration warnings with extensions disabled, to separate your bugs from extension noise.

Best practices

  • Default to Server Components; add "use client" only where interactivity requires it.
  • Keep Client Components small and leaf-like.
  • Pass minimal, serializable props.
  • Use server-only for secrets and data access.
  • Treat hydration warnings as real bugs unless you can name a harmless external cause.

Conclusion

Almost every Server/Client error reduces to a question about a boundary: which side is this code on, and what is crossing it? Once you read errors that way, fixes become small and local: extract a leaf Client Component, pass serializable data or a Server Action, wrap a third-party library, or move a request-only value behind Suspense. The result is an app that ships less JavaScript and fails less often.

Frequently asked questions

+−What does "You're importing a component that needs useState" mean?

You used a client-only feature (state, effects, event handlers, browser APIs) in a Server Component. Add the use client directive to the file that needs it, or extract the interactive part into a small Client Component and keep the parent on the server.

+−Can I pass a function as a prop from a Server to a Client Component?

Not an ordinary function. Props must be serializable. You can pass data, and Server Actions (functions marked with use server) are the exception because they serialize as references.

+−Does use client make the whole subtree client-side?

It marks a module boundary: that file and everything it imports run on the client. But Server Components can still be passed to a Client Component as children or props, so the subtree does not have to become client code.

+−Why do I get a hydration mismatch error?

The HTML rendered on the server differs from what the client renders on its first pass. Common causes are Date or Math.random in render, locale-dependent formatting, reading window or localStorage during render, invalid HTML nesting, and browser extensions that modify the DOM.

+−How do I use a third-party component that needs state or effects?

If the package does not include use client, wrap it in your own file that has the directive and re-export it. Then import that wrapper from Server Components.

+−Where should context providers go?

Providers are Client Components. Create a client file that renders the provider and accepts children, then render it as deep in the tree as it needs to be. Children passed through remain Server Components.

+−How do I stop server-only code, like database access, from leaking to the client?

Add import 'server-only' at the top of modules that must never run in the browser. The build fails if a Client Component imports them, and you avoid shipping secrets by accident.

Further reading

  • nextjs.org/docs/app

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Managing API Caching and Data Fetching in Next.js

A mental model for Next.js caching layers and a repeatable pattern for fetching, caching and revalidating API data.

Next.js, React & TypeScriptNovember 28, 202611 min readIntermediate

Implementing SEO-Friendly Dynamic Routes in Next.js

Static params, metadata, canonicals and a sitemap: the full SEO setup for [slug] routes.

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Handling Authentication and Protected Routes in Next.js

Optimistic checks in proxy, real checks next to the data: a layered approach to protecting routes.

Built by Hamza Janzaib